blob: 151f0c1261795f24d8c88037bed480f7a0bccb50 [file] [log] [blame]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001
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
10The :mod:`mutex` module defines a class that allows mutual-exclusion via
Mark Summerfieldfcb444a2007-09-04 08:16:15 +000011acquiring and releasing locks. It does not require (or imply)
12:mod:`threading` or multi-tasking, though it could be useful for those
13purposes.
Georg Brandl8ec7f652007-08-15 14:28:01 +000014
15The :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
35Mutex 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