The thread module (cont)

Thread termination

  • Thread silently exits when the function returns.
  • Thread can explicitly exit by calling thread.exit() or sys.exit().
  • Uncaught exception causes thread termination (and prints error message).
  • However, other threads continue to run even if one had an error.

Simple locks

  • allocate_lock(). Creates a lock object, initially unlocked.
     import thread
     lk = thread.allocate_lock()
     def foo():
         lk.acquire()       # Acquire the lock
         critical section
         lk.release()       # Release the lock 
  • Only one thread can acquire the lock at once.
  • Threads block indefinitely until lock becomes available.
  • You might use this if two or more threads were allowed to update a shared data structure.
<<< O'Reilly OSCON 2000, Advanced Python Programming, Slide 69
July 17, 2000, beazley@cs.uchicago.edu
>>>