blob: 523692f0667c2b6dc705339406aa68eec2cd5387 [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
11acquiring and releasing locks. It does not require (or imply) threading or
12multi-tasking, though it could be useful for those purposes.
13
14The :mod:`mutex` module defines the following class:
15
16
17.. class:: mutex()
18
19 Create a new (unlocked) mutex.
20
21 A mutex has two pieces of state --- a "locked" bit and a queue. When the mutex
22 is not locked, the queue is empty. Otherwise, the queue contains zero or more
23 ``(function, argument)`` pairs representing functions (or methods) waiting to
24 acquire the lock. When the mutex is unlocked while the queue is not empty, the
25 first queue entry is removed and its ``function(argument)`` pair called,
26 implying it now has the lock.
27
28 Of course, no multi-threading is implied -- hence the funny interface for
29 :meth:`lock`, where a function is called once the lock is acquired.
30
31
32.. _mutex-objects:
33
34Mutex Objects
35-------------
36
37:class:`mutex` objects have following methods:
38
39
40.. method:: mutex.test()
41
42 Check whether the mutex is locked.
43
44
45.. method:: mutex.testandset()
46
47 "Atomic" test-and-set, grab the lock if it is not set, and return ``True``,
48 otherwise, return ``False``.
49
50
51.. method:: mutex.lock(function, argument)
52
53 Execute ``function(argument)``, unless the mutex is locked. In the case it is
54 locked, place the function and argument on the queue. See :meth:`unlock` for
55 explanation of when ``function(argument)`` is executed in that case.
56
57
58.. method:: mutex.unlock()
59
60 Unlock the mutex if queue is empty, otherwise execute the first element in the
61 queue.
62