| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1 |  | 
 | 2 | :mod:`mutex` --- Mutual exclusion support | 
 | 3 | ========================================= | 
 | 4 |  | 
 | 5 | .. module:: mutex | 
 | 6 |    :synopsis: Lock and queue for mutual exclusion. | 
 | 7 | .. sectionauthor:: Moshe Zadka <moshez@zadka.site.co.il> | 
 | 8 |  | 
 | 9 |  | 
 | 10 | The :mod:`mutex` module defines a class that allows mutual-exclusion via | 
| Thomas Wouters | 89d996e | 2007-09-08 17:39:28 +0000 | [diff] [blame] | 11 | acquiring and releasing locks. It does not require (or imply) | 
 | 12 | :mod:`threading` or multi-tasking, though it could be useful for those | 
 | 13 | purposes. | 
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 14 |  | 
 | 15 | The :mod:`mutex` module defines the following class: | 
 | 16 |  | 
 | 17 |  | 
 | 18 | .. class:: mutex() | 
 | 19 |  | 
 | 20 |    Create a new (unlocked) mutex. | 
 | 21 |  | 
 | 22 |    A mutex has two pieces of state --- a "locked" bit and a queue. When the mutex | 
 | 23 |    is not locked, the queue is empty. Otherwise, the queue contains zero or more | 
 | 24 |    ``(function, argument)`` pairs representing functions (or methods) waiting to | 
 | 25 |    acquire the lock. When the mutex is unlocked while the queue is not empty, the | 
 | 26 |    first queue entry is removed and its  ``function(argument)`` pair called, | 
 | 27 |    implying it now has the lock. | 
 | 28 |  | 
 | 29 |    Of course, no multi-threading is implied -- hence the funny interface for | 
 | 30 |    :meth:`lock`, where a function is called once the lock is acquired. | 
 | 31 |  | 
 | 32 |  | 
 | 33 | .. _mutex-objects: | 
 | 34 |  | 
 | 35 | Mutex Objects | 
 | 36 | ------------- | 
 | 37 |  | 
 | 38 | :class:`mutex` objects have following methods: | 
 | 39 |  | 
 | 40 |  | 
 | 41 | .. method:: mutex.test() | 
 | 42 |  | 
 | 43 |    Check whether the mutex is locked. | 
 | 44 |  | 
 | 45 |  | 
 | 46 | .. method:: mutex.testandset() | 
 | 47 |  | 
 | 48 |    "Atomic" test-and-set, grab the lock if it is not set, and return ``True``, | 
 | 49 |    otherwise, return ``False``. | 
 | 50 |  | 
 | 51 |  | 
 | 52 | .. method:: mutex.lock(function, argument) | 
 | 53 |  | 
 | 54 |    Execute ``function(argument)``, unless the mutex is locked. In the case it is | 
 | 55 |    locked, place the function and argument on the queue. See :meth:`unlock` for | 
 | 56 |    explanation of when ``function(argument)`` is executed in that case. | 
 | 57 |  | 
 | 58 |  | 
 | 59 | .. method:: mutex.unlock() | 
 | 60 |  | 
 | 61 |    Unlock the mutex if queue is empty, otherwise execute the first element in the | 
 | 62 |    queue. | 
 | 63 |  |