14.2 The thread Module

The only part of the thread module that your code should use directly is the lock objects that module thread supplies. Locks are simple thread-synchronization primitives. Technically, thread's locks are non-reentrant and unowned: they do not keep track of what thread last locked them, so there is no specific owner thread for a lock. A lock is in one of two states, locked or unlocked.

To get a new lock object (in the unlocked state), call the function named allocate_lock without arguments. This function is supplied by both modules thread and threading. A lock object L supplies three methods.



When wait is True, acquire locks L. If L is already locked, the calling thread suspends and waits until L is unlocked, then locks L. Even if the calling thread was the one that last locked L, it still suspends and waits until another thread releases L. When wait is False and L is unlocked, acquire locks L and returns True. When wait is False and L is locked, acquire does not affect L, and returns False.


L.locked(  )

Returns True if L is locked, otherwise False.


L.release(  )

Unlocks L, which must be locked. When L is locked, any thread may call L.release, not just the thread that last locked L. When more than one thread is waiting on L (i.e., has called L.acquire, finding L locked, and is now waiting for L to be unlocked), release wakes up an arbitrary waiting thread. The thread that calls release is not suspended: it remains ready and continues to execute.

    Part III: Python Library and Extension Modules