Rietveld Code Review Tool
Help | Bug tracker | Discussion group | Source code | Sign in
(86062)

Side by Side Diff: Doc/library/threading.rst

Issue 10968: threading.Timer should be a class so that it can be derived
Patch Set: Created 8 years, 3 months ago
Left:
Right:
Use n/p to move between diff chunks; N/P to move between comments. Please Sign in to add in-line comments.
Jump to:
View unified diff | Download patch
« no previous file with comments | « Doc/library/multiprocessing.rst ('k') | no next file » | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
1 :mod:`threading` --- Thread-based parallelism 1 :mod:`threading` --- Thread-based parallelism
2 ============================================= 2 =============================================
3 3
4 .. module:: threading 4 .. module:: threading
5 :synopsis: Thread-based parallelism. 5 :synopsis: Thread-based parallelism.
6 6
7 **Source code:** :source:`Lib/threading.py` 7 **Source code:** :source:`Lib/threading.py`
8 8
9 -------------- 9 --------------
10 10
11 This module constructs higher-level threading interfaces on top of the lower 11 This module constructs higher-level threading interfaces on top of the lower
12 level :mod:`_thread` module. See also the :mod:`queue` module. 12 level :mod:`_thread` module. See also the :mod:`queue` module.
13 13
14 The :mod:`dummy_threading` module is provided for situations where 14 The :mod:`dummy_threading` module is provided for situations where
15 :mod:`threading` cannot be used because :mod:`_thread` is missing. 15 :mod:`threading` cannot be used because :mod:`_thread` is missing.
16 16
17 .. note:: 17 .. note::
18 18
19 While they are not listed below, the ``camelCase`` names used for some 19 While they are not listed below, the ``camelCase`` names used for some
20 methods and functions in this module in the Python 2.x series are still 20 methods and functions in this module in the Python 2.x series are still
21 supported by this module. 21 supported by this module.
22 22
23 23
24 This module defines the following functions and objects: 24 This module defines the following functions:
25 25
26 26
27 .. function:: active_count() 27 .. function:: active_count()
28 28
29 Return the number of :class:`Thread` objects currently alive. The returned 29 Return the number of :class:`Thread` objects currently alive. The returned
30 count is equal to the length of the list returned by :func:`.enumerate`. 30 count is equal to the length of the list returned by :func:`.enumerate`.
31
32
33 .. function:: Condition()
34 :noindex:
35
36 A factory function that returns a new condition variable object. A condition
37 variable allows one or more threads to wait until they are notified by anothe r
38 thread.
39
40 See :ref:`condition-objects`.
41 31
42 32
43 .. function:: current_thread() 33 .. function:: current_thread()
44 34
45 Return the current :class:`Thread` object, corresponding to the caller's thre ad 35 Return the current :class:`Thread` object, corresponding to the caller's thre ad
46 of control. If the caller's thread of control was not created through the 36 of control. If the caller's thread of control was not created through the
47 :mod:`threading` module, a dummy thread object with limited functionality is 37 :mod:`threading` module, a dummy thread object with limited functionality is
48 returned. 38 returned.
49 39
50 40
51 .. function:: get_ident() 41 .. function:: get_ident()
52 42
53 Return the 'thread identifier' of the current thread. This is a nonzero 43 Return the 'thread identifier' of the current thread. This is a nonzero
54 integer. Its value has no direct meaning; it is intended as a magic cookie 44 integer. Its value has no direct meaning; it is intended as a magic cookie
55 to be used e.g. to index a dictionary of thread-specific data. Thread 45 to be used e.g. to index a dictionary of thread-specific data. Thread
56 identifiers may be recycled when a thread exits and another thread is 46 identifiers may be recycled when a thread exits and another thread is
57 created. 47 created.
58 48
59 .. versionadded:: 3.3 49 .. versionadded:: 3.3
60 50
61 51
62 .. function:: enumerate() 52 .. function:: enumerate()
63 53
64 Return a list of all :class:`Thread` objects currently alive. The list 54 Return a list of all :class:`Thread` objects currently alive. The list
65 includes daemonic threads, dummy thread objects created by 55 includes daemonic threads, dummy thread objects created by
66 :func:`current_thread`, and the main thread. It excludes terminated threads 56 :func:`current_thread`, and the main thread. It excludes terminated threads
67 and threads that have not yet been started. 57 and threads that have not yet been started.
68
69
70 .. function:: Event()
71 :noindex:
72
73 A factory function that returns a new event object. An event manages a flag
74 that can be set to true with the :meth:`~Event.set` method and reset to false
75 with the :meth:`clear` method. The :meth:`wait` method blocks until the flag
76 is true.
77
78 See :ref:`event-objects`.
79
80
81 .. class:: local
82
83 A class that represents thread-local data. Thread-local data are data whose
84 values are thread specific. To manage thread-local data, just create an
85 instance of :class:`local` (or a subclass) and store attributes on it::
86
87 mydata = threading.local()
88 mydata.x = 1
89
90 The instance's values will be different for separate threads.
91
92 For more details and extensive examples, see the documentation string of the
93 :mod:`_threading_local` module.
94
95
96 .. function:: Lock()
97
98 A factory function that returns a new primitive lock object. Once a thread h as
99 acquired it, subsequent attempts to acquire it block, until it is released; a ny
100 thread may release it.
101
102 See :ref:`lock-objects`.
103
104
105 .. function:: RLock()
106
107 A factory function that returns a new reentrant lock object. A reentrant lock
108 must be released by the thread that acquired it. Once a thread has acquired a
109 reentrant lock, the same thread may acquire it again without blocking; the
110 thread must release it once for each time it has acquired it.
111
112 See :ref:`rlock-objects`.
113
114
115 .. function:: Semaphore(value=1)
116 :noindex:
117
118 A factory function that returns a new semaphore object. A semaphore manages a
119 counter representing the number of :meth:`release` calls minus the number of
120 :meth:`acquire` calls, plus an initial value. The :meth:`acquire` method bloc ks
121 if necessary until it can return without making the counter negative. If not
122 given, *value* defaults to 1.
123
124 See :ref:`semaphore-objects`.
125
126
127 .. function:: BoundedSemaphore(value=1)
128
129 A factory function that returns a new bounded semaphore object. A bounded
130 semaphore checks to make sure its current value doesn't exceed its initial
131 value. If it does, :exc:`ValueError` is raised. In most situations semaphore s
132 are used to guard resources with limited capacity. If the semaphore is relea sed
133 too many times it's a sign of a bug. If not given, *value* defaults to 1.
134
135
136 .. class:: Thread
137 :noindex:
138
139 A class that represents a thread of control. This class can be safely
140 subclassed in a limited fashion.
141
142 See :ref:`thread-objects`.
143
144
145 .. class:: Timer
146 :noindex:
147
148 A thread that executes a function after a specified interval has passed.
149
150 See :ref:`timer-objects`.
151 58
152 59
153 .. function:: settrace(func) 60 .. function:: settrace(func)
154 61
155 .. index:: single: trace function 62 .. index:: single: trace function
156 63
157 Set a trace function for all threads started from the :mod:`threading` module . 64 Set a trace function for all threads started from the :mod:`threading` module .
158 The *func* will be passed to :func:`sys.settrace` for each thread, before it s 65 The *func* will be passed to :func:`sys.settrace` for each thread, before it s
159 :meth:`run` method is called. 66 :meth:`run` method is called.
160 67
(...skipping 30 matching lines...) Expand all
191 .. data:: TIMEOUT_MAX 98 .. data:: TIMEOUT_MAX
192 99
193 The maximum value allowed for the *timeout* parameter of blocking functions 100 The maximum value allowed for the *timeout* parameter of blocking functions
194 (:meth:`Lock.acquire`, :meth:`RLock.acquire`, :meth:`Condition.wait`, etc.). 101 (:meth:`Lock.acquire`, :meth:`RLock.acquire`, :meth:`Condition.wait`, etc.).
195 Specifying a timeout greater than this value will raise an 102 Specifying a timeout greater than this value will raise an
196 :exc:`OverflowError`. 103 :exc:`OverflowError`.
197 104
198 .. versionadded:: 3.2 105 .. versionadded:: 3.2
199 106
200 107
201 Detailed interfaces for the objects are documented below. 108 This module defines a number of classes. Most of them are documented in detail
109 later in this document.
110
111 .. class:: local
112
113 A class that represents thread-local data. Thread-local data are data whose
114 values are thread specific. To manage thread-local data, just create an
115 instance of :class:`local` (or a subclass) and store attributes on it::
116
117 mydata = threading.local()
118 mydata.x = 1
119
120 The instance's values will be different for separate threads.
121
122 For more details and extensive examples, see the documentation string of the
123 :mod:`_threading_local` module.
124
202 125
203 The design of this module is loosely based on Java's threading model. However, 126 The design of this module is loosely based on Java's threading model. However,
204 where Java makes locks and condition variables basic behavior of every object, 127 where Java makes locks and condition variables basic behavior of every object,
205 they are separate objects in Python. Python's :class:`Thread` class supports a 128 they are separate objects in Python. Python's :class:`Thread` class supports a
206 subset of the behavior of Java's Thread class; currently, there are no 129 subset of the behavior of Java's Thread class; currently, there are no
207 priorities, no thread groups, and threads cannot be destroyed, stopped, 130 priorities, no thread groups, and threads cannot be destroyed, stopped,
208 suspended, resumed, or interrupted. The static methods of Java's Thread class, 131 suspended, resumed, or interrupted. The static methods of Java's Thread class,
209 when implemented, are mapped to module-level functions. 132 when implemented, are mapped to module-level functions.
210 133
211 All of the methods described below are executed atomically. 134 All of the methods described below are executed atomically.
212 135
213 136
214 .. _thread-objects: 137 .. _thread-objects:
215 138
216 Thread Objects 139 Thread Objects
217 -------------- 140 --------------
218 141
219 This class represents an activity that is run in a separate thread of control. 142 The :class:`Thread` class represents an activity that is run in a separate
143 thread of control.
220 There are two ways to specify the activity: by passing a callable object to the 144 There are two ways to specify the activity: by passing a callable object to the
221 constructor, or by overriding the :meth:`run` method in a subclass. No other 145 constructor, or by overriding the :meth:`run` method in a subclass. No other
222 methods (except for the constructor) should be overridden in a subclass. In 146 methods (except for the constructor) should be overridden in a subclass. In
223 other words, *only* override the :meth:`__init__` and :meth:`run` methods of 147 other words, *only* override the :meth:`__init__` and :meth:`run` methods of
224 this class. 148 this class.
225 149
226 Once a thread object is created, its activity must be started by calling the 150 Once a thread object is created, its activity must be started by calling the
227 thread's :meth:`start` method. This invokes the :meth:`run` method in a 151 thread's :meth:`start` method. This invokes the :meth:`run` method in a
228 separate thread of control. 152 separate thread of control.
229 153
(...skipping 17 matching lines...) Expand all
247 control in the Python program. It is not a daemon thread. 171 control in the Python program. It is not a daemon thread.
248 172
249 There is the possibility that "dummy thread objects" are created. These are 173 There is the possibility that "dummy thread objects" are created. These are
250 thread objects corresponding to "alien threads", which are threads of control 174 thread objects corresponding to "alien threads", which are threads of control
251 started outside the threading module, such as directly from C code. Dummy 175 started outside the threading module, such as directly from C code. Dummy
252 thread objects have limited functionality; they are always considered alive and 176 thread objects have limited functionality; they are always considered alive and
253 daemonic, and cannot be :meth:`join`\ ed. They are never deleted, since it is 177 daemonic, and cannot be :meth:`join`\ ed. They are never deleted, since it is
254 impossible to detect the termination of alien threads. 178 impossible to detect the termination of alien threads.
255 179
256 180
257 .. class:: Thread(group=None, target=None, name=None, args=(), kwargs={}, 181 .. class:: Thread(group=None, target=None, name=None, args=(), kwargs={}, \
258 verbose=None, *, daemon=None) 182 verbose=None, *, daemon=None)
259 183
260 This constructor should always be called with keyword arguments. Arguments 184 This constructor should always be called with keyword arguments. Arguments
261 are: 185 are:
262 186
263 *group* should be ``None``; reserved for future extension when a 187 *group* should be ``None``; reserved for future extension when a
264 :class:`ThreadGroup` class is implemented. 188 :class:`ThreadGroup` class is implemented.
265 189
266 *target* is the callable object to be invoked by the :meth:`run` method. 190 *target* is the callable object to be invoked by the :meth:`run` method.
267 Defaults to ``None``, meaning nothing is called. 191 Defaults to ``None``, meaning nothing is called.
(...skipping 11 matching lines...) Expand all
279 If not ``None``, *daemon* explicitly sets whether the thread is daemonic. 203 If not ``None``, *daemon* explicitly sets whether the thread is daemonic.
280 If ``None`` (the default), the daemonic property is inherited from the 204 If ``None`` (the default), the daemonic property is inherited from the
281 current thread. 205 current thread.
282 206
283 If the subclass overrides the constructor, it must make sure to invoke the 207 If the subclass overrides the constructor, it must make sure to invoke the
284 base class constructor (``Thread.__init__()``) before doing anything else to 208 base class constructor (``Thread.__init__()``) before doing anything else to
285 the thread. 209 the thread.
286 210
287 .. versionchanged:: 3.3 211 .. versionchanged:: 3.3
288 Added the *daemon* argument. 212 Added the *daemon* argument.
213
214 .. versionchanged:: 3.3
215 ``Thread`` used to be a factory function rather than the class itself.
ezio.melotti 2011/09/17 20:49:11 Something about this sentence sounds wrong to me.
289 216
290 .. method:: start() 217 .. method:: start()
291 218
292 Start the thread's activity. 219 Start the thread's activity.
293 220
294 It must be called at most once per thread object. It arranges for the 221 It must be called at most once per thread object. It arranges for the
295 object's :meth:`run` method to be invoked in a separate thread of control. 222 object's :meth:`run` method to be invoked in a separate thread of control.
296 223
297 This method will raise a :exc:`RuntimeError` if called more than once 224 This method will raise a :exc:`RuntimeError` if called more than once
298 on the same thread object. 225 on the same thread object.
(...skipping 106 matching lines...) Expand 10 before | Expand all | Expand 10 after
405 :meth:`release` method should only be called in the locked state; it changes the 332 :meth:`release` method should only be called in the locked state; it changes the
406 state to unlocked and returns immediately. If an attempt is made to release an 333 state to unlocked and returns immediately. If an attempt is made to release an
407 unlocked lock, a :exc:`RuntimeError` will be raised. 334 unlocked lock, a :exc:`RuntimeError` will be raised.
408 335
409 When more than one thread is blocked in :meth:`acquire` waiting for the state to 336 When more than one thread is blocked in :meth:`acquire` waiting for the state to
410 turn to unlocked, only one thread proceeds when a :meth:`release` call resets 337 turn to unlocked, only one thread proceeds when a :meth:`release` call resets
411 the state to unlocked; which one of the waiting threads proceeds is not defined, 338 the state to unlocked; which one of the waiting threads proceeds is not defined,
412 and may vary across implementations. 339 and may vary across implementations.
413 340
414 All methods are executed atomically. 341 All methods are executed atomically.
342
343
344 .. class:: Lock()
345
346 The class implementing primitive lock objects. Once a thread has acquired a
347 lock, subsequent attempts to acquire it block, until it is released; any
348 thread may release it.
349
350 .. versionchanged:: 3.3
351 ``Lock`` used to be a factory function rather than the class itself.
415 352
416 353
417 .. method:: Lock.acquire(blocking=True, timeout=-1) 354 .. method:: Lock.acquire(blocking=True, timeout=-1)
418 355
419 Acquire a lock, blocking or non-blocking. 356 Acquire a lock, blocking or non-blocking.
420 357
421 When invoked without arguments, block until the lock is unlocked, then set it to 358 When invoked without arguments, block until the lock is unlocked, then set it to
422 locked, and return true. 359 locked, and return true.
423 360
424 When invoked with the *blocking* argument set to true, do the same thing as w hen 361 When invoked with the *blocking* argument set to true, do the same thing as w hen
(...skipping 42 matching lines...) Expand 10 before | Expand all | Expand 10 after
467 and "recursion level" in addition to the locked/unlocked state used by primitive 404 and "recursion level" in addition to the locked/unlocked state used by primitive
468 locks. In the locked state, some thread owns the lock; in the unlocked state, 405 locks. In the locked state, some thread owns the lock; in the unlocked state,
469 no thread owns it. 406 no thread owns it.
470 407
471 To lock the lock, a thread calls its :meth:`acquire` method; this returns once 408 To lock the lock, a thread calls its :meth:`acquire` method; this returns once
472 the thread owns the lock. To unlock the lock, a thread calls its 409 the thread owns the lock. To unlock the lock, a thread calls its
473 :meth:`release` method. :meth:`acquire`/:meth:`release` call pairs may be 410 :meth:`release` method. :meth:`acquire`/:meth:`release` call pairs may be
474 nested; only the final :meth:`release` (the :meth:`release` of the outermost 411 nested; only the final :meth:`release` (the :meth:`release` of the outermost
475 pair) resets the lock to unlocked and allows another thread blocked in 412 pair) resets the lock to unlocked and allows another thread blocked in
476 :meth:`acquire` to proceed. 413 :meth:`acquire` to proceed.
414
415
416 .. class:: RLock()
417
418 This class implements reentrant lock objects. A reentrant lock must be
419 released by the thread that acquired it. Once a thread has acquired a
420 reentrant lock, the same thread may acquire it again without blocking; the
421 thread must release it once for each time it has acquired it.
422
423 .. versionchanged:: 3.3
424 ``RLock`` used to be a factory function rather than the class itself.
477 425
478 426
479 .. method:: RLock.acquire(blocking=True, timeout=-1) 427 .. method:: RLock.acquire(blocking=True, timeout=-1)
480 428
481 Acquire a lock, blocking or non-blocking. 429 Acquire a lock, blocking or non-blocking.
482 430
483 When invoked without arguments: if this thread already owns the lock, increme nt 431 When invoked without arguments: if this thread already owns the lock, increme nt
484 the recursion level by one, and return immediately. Otherwise, if another 432 the recursion level by one, and return immediately. Otherwise, if another
485 thread owns the lock, block until the lock is unlocked. Once the lock is 433 thread owns the lock, block until the lock is unlocked. Once the lock is
486 unlocked (not owned by any thread), then grab ownership, set the recursion le vel 434 unlocked (not owned by any thread), then grab ownership, set the recursion le vel
(...skipping 89 matching lines...) Expand 10 before | Expand all | Expand 10 after
576 524
577 Note: Condition variables can be, depending on the implementation, subject 525 Note: Condition variables can be, depending on the implementation, subject
578 to both spurious wakeups (when :meth:`wait` returns without a :meth:`notify` 526 to both spurious wakeups (when :meth:`wait` returns without a :meth:`notify`
579 call) and stolen wakeups (when another thread acquires the lock before the 527 call) and stolen wakeups (when another thread acquires the lock before the
580 awoken thread.) For this reason, it is always necessary to verify the state 528 awoken thread.) For this reason, it is always necessary to verify the state
581 the thread is waiting for when :meth:`wait` returns and optionally repeat 529 the thread is waiting for when :meth:`wait` returns and optionally repeat
582 the call as often as necessary. 530 the call as often as necessary.
583 531
584 532
585 .. class:: Condition(lock=None) 533 .. class:: Condition(lock=None)
534
535 This class implements condition variable objects. A condition variable
536 allows one or more threads to wait until they are notified by another thread.
586 537
587 If the *lock* argument is given and not ``None``, it must be a :class:`Lock` 538 If the *lock* argument is given and not ``None``, it must be a :class:`Lock`
588 or :class:`RLock` object, and it is used as the underlying lock. Otherwise, 539 or :class:`RLock` object, and it is used as the underlying lock. Otherwise,
589 a new :class:`RLock` object is created and used as the underlying lock. 540 a new :class:`RLock` object is created and used as the underlying lock.
590 541
542 .. versionchanged:: 3.3
543 ``Condition`` used to be a factory function rather than the class itself.
544
591 .. method:: acquire(*args) 545 .. method:: acquire(*args)
592 546
593 Acquire the underlying lock. This method calls the corresponding method on 547 Acquire the underlying lock. This method calls the corresponding method on
594 the underlying lock; the return value is whatever that method returns. 548 the underlying lock; the return value is whatever that method returns.
595 549
596 .. method:: release() 550 .. method:: release()
597 551
598 Release the underlying lock. This method calls the corresponding method on 552 Release the underlying lock. This method calls the corresponding method on
599 the underlying lock; there is no return value. 553 the underlying lock; there is no return value.
600 554
(...skipping 89 matching lines...) Expand 10 before | Expand all | Expand 10 after
690 science, invented by the early Dutch computer scientist Edsger W. Dijkstra (he 644 science, invented by the early Dutch computer scientist Edsger W. Dijkstra (he
691 used :meth:`P` and :meth:`V` instead of :meth:`acquire` and :meth:`release`). 645 used :meth:`P` and :meth:`V` instead of :meth:`acquire` and :meth:`release`).
692 646
693 A semaphore manages an internal counter which is decremented by each 647 A semaphore manages an internal counter which is decremented by each
694 :meth:`acquire` call and incremented by each :meth:`release` call. The counter 648 :meth:`acquire` call and incremented by each :meth:`release` call. The counter
695 can never go below zero; when :meth:`acquire` finds that it is zero, it blocks, 649 can never go below zero; when :meth:`acquire` finds that it is zero, it blocks,
696 waiting until some other thread calls :meth:`release`. 650 waiting until some other thread calls :meth:`release`.
697 651
698 652
699 .. class:: Semaphore(value=1) 653 .. class:: Semaphore(value=1)
654
655 This class implements semaphore objects. A semaphore manages a counter
656 representing the number of :meth:`release` calls minus the number of
657 :meth:`acquire` calls, plus an initial value. The :meth:`acquire` method
658 blocks if necessary until it can return without making the counter negative.
659 If not given, *value* defaults to 1.
700 660
701 The optional argument gives the initial *value* for the internal counter; it 661 The optional argument gives the initial *value* for the internal counter; it
702 defaults to ``1``. If the *value* given is less than 0, :exc:`ValueError` is 662 defaults to ``1``. If the *value* given is less than 0, :exc:`ValueError` is
703 raised. 663 raised.
704 664
665 .. versionchanged:: 3.3
666 ``Semaphore`` used to be a factory function rather than the class itself.
667
705 .. method:: acquire(blocking=True, timeout=None) 668 .. method:: acquire(blocking=True, timeout=None)
706 669
707 Acquire a semaphore. 670 Acquire a semaphore.
708 671
709 When invoked without arguments: if the internal counter is larger than 672 When invoked without arguments: if the internal counter is larger than
710 zero on entry, decrement it by one and return immediately. If it is zero 673 zero on entry, decrement it by one and return immediately. If it is zero
711 on entry, block, waiting until some other thread has called 674 on entry, block, waiting until some other thread has called
712 :meth:`release` to make it larger than zero. This is done with proper 675 :meth:`release` to make it larger than zero. This is done with proper
713 interlocking so that if multiple :meth:`acquire` calls are blocked, 676 interlocking so that if multiple :meth:`acquire` calls are blocked,
714 :meth:`release` will wake exactly one of them up. The implementation may 677 :meth:`release` will wake exactly one of them up. The implementation may
715 pick one at random, so the order in which blocked threads are awakened 678 pick one at random, so the order in which blocked threads are awakened
716 should not be relied on. Returns true (or blocks indefinitely). 679 should not be relied on. Returns true (or blocks indefinitely).
717 680
718 When invoked with *blocking* set to false, do not block. If a call 681 When invoked with *blocking* set to false, do not block. If a call
719 without an argument would block, return false immediately; otherwise, 682 without an argument would block, return false immediately; otherwise,
720 do the same thing as when called without arguments, and return true. 683 do the same thing as when called without arguments, and return true.
721 684
722 When invoked with a *timeout* other than None, it will block for at 685 When invoked with a *timeout* other than None, it will block for at
723 most *timeout* seconds. If acquire does not complete successfully in 686 most *timeout* seconds. If acquire does not complete successfully in
724 that interval, return false. Return true otherwise. 687 that interval, return false. Return true otherwise.
725 688
726 .. versionchanged:: 3.2 689 .. versionchanged:: 3.2
727 The *timeout* parameter is new. 690 The *timeout* parameter is new.
728 691
729 .. method:: release() 692 .. method:: release()
730 693
731 Release a semaphore, incrementing the internal counter by one. When it 694 Release a semaphore, incrementing the internal counter by one. When it
732 was zero on entry and another thread is waiting for it to become larger 695 was zero on entry and another thread is waiting for it to become larger
733 than zero again, wake up that thread. 696 than zero again, wake up that thread.
697
698
699 .. class:: BoundedSemaphore(value=1)
700
701 Class implementing bounded semaphore objects. A bounded semaphore checks to
702 make sure its current value doesn't exceed its initial value. If it does,
703 :exc:`ValueError` is raised. In most situations semaphores are used to guard
704 resources with limited capacity. If the semaphore is released too many times
705 it's a sign of a bug. If not given, *value* defaults to 1.
706
707 .. versionchanged:: 3.3
708 ``BoundedSemaphore`` used to be a factory function rather than the class
709 itself.
734 710
735 711
736 .. _semaphore-examples: 712 .. _semaphore-examples:
737 713
738 :class:`Semaphore` Example 714 :class:`Semaphore` Example
739 ^^^^^^^^^^^^^^^^^^^^^^^^^^ 715 ^^^^^^^^^^^^^^^^^^^^^^^^^^
740 716
741 Semaphores are often used to guard resources with limited capacity, for example, 717 Semaphores are often used to guard resources with limited capacity, for example,
742 a database server. In any situation where the size of the resource is fixed, 718 a database server. In any situation where the size of the resource is fixed,
743 you should use a bounded semaphore. Before spawning any worker threads, your 719 you should use a bounded semaphore. Before spawning any worker threads, your
744 main thread would initialize the semaphore:: 720 main thread would initialize the semaphore::
745 721
746 maxconnections = 5 722 maxconnections = 5
747 ... 723 # ...
748 pool_sema = BoundedSemaphore(value=maxconnections) 724 pool_sema = BoundedSemaphore(value=maxconnections)
749 725
750 Once spawned, worker threads call the semaphore's acquire and release methods 726 Once spawned, worker threads call the semaphore's acquire and release methods
751 when they need to connect to the server:: 727 when they need to connect to the server::
752 728
753 pool_sema.acquire() 729 pool_sema.acquire()
754 conn = connectdb() 730 conn = connectdb()
755 ... use connection ... 731 # ... use connection ...
756 conn.close() 732 conn.close()
757 pool_sema.release() 733 pool_sema.release()
758 734
759 The use of a bounded semaphore reduces the chance that a programming error which 735 The use of a bounded semaphore reduces the chance that a programming error which
760 causes the semaphore to be released more than it's acquired will go undetected. 736 causes the semaphore to be released more than it's acquired will go undetected.
761 737
762 738
763 .. _event-objects: 739 .. _event-objects:
764 740
765 Event Objects 741 Event Objects
766 ------------- 742 -------------
767 743
768 This is one of the simplest mechanisms for communication between threads: one 744 This is one of the simplest mechanisms for communication between threads: one
769 thread signals an event and other threads wait for it. 745 thread signals an event and other threads wait for it.
770 746
771 An event object manages an internal flag that can be set to true with the 747 An event object manages an internal flag that can be set to true with the
772 :meth:`~Event.set` method and reset to false with the :meth:`clear` method. The 748 :meth:`~Event.set` method and reset to false with the :meth:`clear` method. The
773 :meth:`wait` method blocks until the flag is true. 749 :meth:`wait` method blocks until the flag is true.
774 750
775 751
776 .. class:: Event() 752 .. class:: Event()
777 753
778 The internal flag is initially false. 754 Class implementing event objects. An event manages a flag that can be set to
755 true with the :meth:`~Event.set` method and reset to false with the
756 :meth:`clear` method. The :meth:`wait` method blocks until the flag is true.
757 The flag is initially false.
758
759 .. versionchanged:: 3.3
760 ``Event`` used to be a factory function rather than the class itself.
779 761
780 .. method:: is_set() 762 .. method:: is_set()
781 763
782 Return true if and only if the internal flag is true. 764 Return true if and only if the internal flag is true.
783 765
784 .. method:: set() 766 .. method:: set()
785 767
786 Set the internal flag to true. All threads waiting for it to become true 768 Set the internal flag to true. All threads waiting for it to become true
787 are awakened. Threads that call :meth:`wait` once the flag is true will 769 are awakened. Threads that call :meth:`wait` once the flag is true will
788 not block at all. 770 not block at all.
(...skipping 41 matching lines...) Expand 10 before | Expand all | Expand 10 after
830 print("hello, world") 812 print("hello, world")
831 813
832 t = Timer(30.0, hello) 814 t = Timer(30.0, hello)
833 t.start() # after 30 seconds, "hello, world" will be printed 815 t.start() # after 30 seconds, "hello, world" will be printed
834 816
835 817
836 .. class:: Timer(interval, function, args=[], kwargs={}) 818 .. class:: Timer(interval, function, args=[], kwargs={})
837 819
838 Create a timer that will run *function* with arguments *args* and keyword 820 Create a timer that will run *function* with arguments *args* and keyword
839 arguments *kwargs*, after *interval* seconds have passed. 821 arguments *kwargs*, after *interval* seconds have passed.
822
823 .. versionchanged:: 3.3
824 ``Timer`` used to be a factory function rather than the class itself.
840 825
841 .. method:: cancel() 826 .. method:: cancel()
842 827
843 Stop the timer, and cancel the execution of the timer's action. This will 828 Stop the timer, and cancel the execution of the timer's action. This will
844 only work if the timer is still in its waiting stage. 829 only work if the timer is still in its waiting stage.
845 830
846 831
847 Barrier Objects 832 Barrier Objects
848 --------------- 833 ---------------
849 834
(...skipping 133 matching lines...) Expand 10 before | Expand all | Expand 10 after
983 the spawned thread directly or indirectly attempts to import a module. 968 the spawned thread directly or indirectly attempts to import a module.
984 * Secondly, all import attempts must be completed before the interpreter 969 * Secondly, all import attempts must be completed before the interpreter
985 starts shutting itself down. This can be most easily achieved by only 970 starts shutting itself down. This can be most easily achieved by only
986 performing imports from non-daemon threads created through the threading 971 performing imports from non-daemon threads created through the threading
987 module. Daemon threads and threads created directly with the thread 972 module. Daemon threads and threads created directly with the thread
988 module will require some other form of synchronization to ensure they do 973 module will require some other form of synchronization to ensure they do
989 not attempt imports after system shutdown has commenced. Failure to 974 not attempt imports after system shutdown has commenced. Failure to
990 abide by this restriction will lead to intermittent exceptions and 975 abide by this restriction will lead to intermittent exceptions and
991 crashes during interpreter shutdown (as the late imports attempt to 976 crashes during interpreter shutdown (as the late imports attempt to
992 access machinery which is no longer in a valid state). 977 access machinery which is no longer in a valid state).
OLDNEW
« no previous file with comments | « Doc/library/multiprocessing.rst ('k') | no next file » | no next file with comments »

RSS Feeds Recent Issues | This issue
This is Rietveld 894c83f36cb7+