# To enable running multiple programs at the same time import threading # To enable flushing standard out. (That is, printing right away) import sys # To enable yeilding to other methods import time # To enable unlimited counting import itertools # How often to print for each of the methods COUNT_STEP_SIZE = 10000000 PRIMES_STEP_SIZE = 10000 # # Exercise instructions: # # 1. Run this program. Obeserve what it does. Do you have the patience to # wait for "primes" to start? (Please don't feel compelled!) # # 2. In main, switch the order of the calls to count and primes. # Observe what it does. # # 3. To run both programs at the same time, we can use threads. # Create a thread to run the "primes" method using # primes_thread = threading.Thread(target=xxxx,args=yyyy) # where xxx is the name of the method you want to run (just the name!) # and yyyy is a tuple of the arguments you want to pass # # Start your thread using: # primes_thread.start() # # Observe what happens. # # 4. In python, threads do not often yield to each other. To explictly yield t # another thread, you can use # time.sleep(0) # # Observe what happens. # How much slower/faster do the programs run when threading? # # 5. If you have time, you can adjust the parameters. # How fairly are you able to share the processor? # Run two long programs def main(): print "Starting main" sys.stdout.flush() primes(PRIMES_STEP_SIZE) count(COUNT_STEP_SIZE) # Count up, printing current value occassionally def count(step): print "Starting count" sys.stdout.flush() for i in itertools.count(): if i%step==0: print "count: "+str(i) sys.stdout.flush() # Find primes, printing a prime occassionally def primes(step): print "Starting primes" sys.stdout.flush() doPrintNext = True for i in itertools.count(): if i % step == 0: doPrintNext = True isPrime = True; for j in xrange(2,i-1): if i%j == 0: isPrime = False; break; if isPrime and doPrintNext: print "prime: "+str(i) doPrintNext = False sys.stdout.flush() if __name__ == "__main__": main()