Previous Page
Next Page

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 which 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 factory function named allocate_lock without arguments. This function is supplied by both modules thread and threading. A lock object L supplies three methods.

acquire

L.acquire(wait=true)

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.

locked

L.locked( )

Returns TRue if L is locked; otherwise, False.

release

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.



Previous Page
Next Page