Software Design Spring 2007 Processes --------- A process is a running program. It contains: 1) a copy of the program code (the Python interpreter plus the Python program) 2) program data (global variables, but not local variables) 3) initially, one thread of execution, which contains a) a program counter (where in the program are we?) b) a stack of frames (which contain local variables) Threads ------- Abstractly, a thread represents the flow of execution in a program. Usually, a program is executed in a single thread, meaning that at any given time, only one thing is happening. But many interactive programs run multiple threads. For example, at the same time a web browser might 1) download a file 2) render an image 3) play back a sound file 4) update an animated GIF 5) handle events from the user Each of these activities would happen in a separate thread. At a point in time, different threads are executing different parts of the program. Python Threads -------------- Download thread.py from the usual place and run it: from threading import Thread from time import sleep def counter(xs, delay=1): for x in xs: print x sleep(delay) # one thread counts backwards, fast t = Thread(target=counter, args=[range(100, 1, -1), 0.25]) t.start() # the other thread counts forward, slowly counter(range(1, 100), 1) What happens if you use Ctrl-C to try to stop? Q) How can you stop a running thread? A) In general, you can't. Methods that run in the background should check periodically to see if they should keep going. This is a pain. An alternative is the Watcher class in Gui.py. Check it out if you are curious. Q) Why is the Thread interface so horrible? A) I don't know, but you can improve it with something like this: class MyThread(threading.Thread): """this is a wrapper for threading.Thread that improves the syntax for creating and starting threads. See Appendix A of The Little Book of Semaphores, http://greenteapress.com/semaphores/ """ def __init__(self, target, *args): threading.Thread.__init__(self, target=target, args=args) self.start() Then you can create and start a thread the same way you make a Callable: Thread(counter, range(100, 1, -1), 0.25)