blob: e6616dbcd279a5b8112c02c7051f84aaa32646cc [file] [log] [blame]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001:mod:`threading` --- Higher-level threading interface
2=====================================================
3
4.. module:: threading
5 :synopsis: Higher-level threading interface.
6
7
8This module constructs higher-level threading interfaces on top of the lower
9level :mod:`thread` module.
Georg Brandla6168f92008-05-25 07:20:14 +000010See also the :mod:`mutex` and :mod:`Queue` modules.
Georg Brandl8ec7f652007-08-15 14:28:01 +000011
12The :mod:`dummy_threading` module is provided for situations where
13:mod:`threading` cannot be used because :mod:`thread` is missing.
14
Benjamin Petersonf4395602008-06-11 17:50:00 +000015.. note::
16
Benjamin Peterson973e6c22008-09-01 23:12:58 +000017 Starting with Python 2.6, this module provides PEP 8 compliant aliases and
18 properties to replace the ``camelCase`` names that were inspired by Java's
19 threading API. This updated API is compatible with that of the
20 :mod:`multiprocessing` module. However, no schedule has been set for the
21 deprecation of the ``camelCase`` names and they remain fully supported in
22 both Python 2.x and 3.x.
Benjamin Petersonf4395602008-06-11 17:50:00 +000023
Georg Brandl8ec7f652007-08-15 14:28:01 +000024This module defines the following functions and objects:
25
26
Benjamin Peterson0fbcf692008-06-11 17:27:50 +000027.. function:: active_count()
Benjamin Petersonf4395602008-06-11 17:50:00 +000028 activeCount()
Georg Brandl8ec7f652007-08-15 14:28:01 +000029
30 Return the number of :class:`Thread` objects currently alive. The returned
31 count is equal to the length of the list returned by :func:`enumerate`.
32
33
34.. function:: Condition()
35 :noindex:
36
37 A factory function that returns a new condition variable object. A condition
38 variable allows one or more threads to wait until they are notified by another
39 thread.
40
41
Benjamin Peterson0fbcf692008-06-11 17:27:50 +000042.. function:: current_thread()
Benjamin Petersonf4395602008-06-11 17:50:00 +000043 currentThread()
Georg Brandl8ec7f652007-08-15 14:28:01 +000044
45 Return the current :class:`Thread` object, corresponding to the caller's thread
46 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
48 returned.
49
50
51.. function:: enumerate()
52
Benjamin Peterson0fbcf692008-06-11 17:27:50 +000053 Return a list of all :class:`Thread` objects currently alive. The list
54 includes daemonic threads, dummy thread objects created by
55 :func:`current_thread`, and the main thread. It excludes terminated threads
56 and threads that have not yet been started.
Georg Brandl8ec7f652007-08-15 14:28:01 +000057
58
59.. function:: Event()
60 :noindex:
61
62 A factory function that returns a new event object. An event manages a flag
63 that can be set to true with the :meth:`set` method and reset to false with the
64 :meth:`clear` method. The :meth:`wait` method blocks until the flag is true.
65
66
67.. class:: local
68
69 A class that represents thread-local data. Thread-local data are data whose
70 values are thread specific. To manage thread-local data, just create an
71 instance of :class:`local` (or a subclass) and store attributes on it::
72
73 mydata = threading.local()
74 mydata.x = 1
75
76 The instance's values will be different for separate threads.
77
78 For more details and extensive examples, see the documentation string of the
79 :mod:`_threading_local` module.
80
81 .. versionadded:: 2.4
82
83
84.. function:: Lock()
85
86 A factory function that returns a new primitive lock object. Once a thread has
87 acquired it, subsequent attempts to acquire it block, until it is released; any
88 thread may release it.
89
90
91.. function:: RLock()
92
93 A factory function that returns a new reentrant lock object. A reentrant lock
94 must be released by the thread that acquired it. Once a thread has acquired a
95 reentrant lock, the same thread may acquire it again without blocking; the
96 thread must release it once for each time it has acquired it.
97
98
99.. function:: Semaphore([value])
100 :noindex:
101
102 A factory function that returns a new semaphore object. A semaphore manages a
103 counter representing the number of :meth:`release` calls minus the number of
104 :meth:`acquire` calls, plus an initial value. The :meth:`acquire` method blocks
105 if necessary until it can return without making the counter negative. If not
106 given, *value* defaults to 1.
107
108
109.. function:: BoundedSemaphore([value])
110
111 A factory function that returns a new bounded semaphore object. A bounded
112 semaphore checks to make sure its current value doesn't exceed its initial
113 value. If it does, :exc:`ValueError` is raised. In most situations semaphores
114 are used to guard resources with limited capacity. If the semaphore is released
115 too many times it's a sign of a bug. If not given, *value* defaults to 1.
116
117
118.. class:: Thread
119
120 A class that represents a thread of control. This class can be safely
121 subclassed in a limited fashion.
122
123
124.. class:: Timer
125
126 A thread that executes a function after a specified interval has passed.
127
128
129.. function:: settrace(func)
130
131 .. index:: single: trace function
132
133 Set a trace function for all threads started from the :mod:`threading` module.
134 The *func* will be passed to :func:`sys.settrace` for each thread, before its
135 :meth:`run` method is called.
136
137 .. versionadded:: 2.3
138
139
140.. function:: setprofile(func)
141
142 .. index:: single: profile function
143
144 Set a profile function for all threads started from the :mod:`threading` module.
145 The *func* will be passed to :func:`sys.setprofile` for each thread, before its
146 :meth:`run` method is called.
147
148 .. versionadded:: 2.3
149
150
151.. function:: stack_size([size])
152
153 Return the thread stack size used when creating new threads. The optional
154 *size* argument specifies the stack size to be used for subsequently created
155 threads, and must be 0 (use platform or configured default) or a positive
156 integer value of at least 32,768 (32kB). If changing the thread stack size is
157 unsupported, a :exc:`ThreadError` is raised. If the specified stack size is
158 invalid, a :exc:`ValueError` is raised and the stack size is unmodified. 32kB
159 is currently the minimum supported stack size value to guarantee sufficient
160 stack space for the interpreter itself. Note that some platforms may have
161 particular restrictions on values for the stack size, such as requiring a
162 minimum stack size > 32kB or requiring allocation in multiples of the system
163 memory page size - platform documentation should be referred to for more
164 information (4kB pages are common; using multiples of 4096 for the stack size is
165 the suggested approach in the absence of more specific information).
166 Availability: Windows, systems with POSIX threads.
167
168 .. versionadded:: 2.5
169
170Detailed interfaces for the objects are documented below.
171
172The design of this module is loosely based on Java's threading model. However,
173where Java makes locks and condition variables basic behavior of every object,
174they are separate objects in Python. Python's :class:`Thread` class supports a
175subset of the behavior of Java's Thread class; currently, there are no
176priorities, no thread groups, and threads cannot be destroyed, stopped,
177suspended, resumed, or interrupted. The static methods of Java's Thread class,
178when implemented, are mapped to module-level functions.
179
180All of the methods described below are executed atomically.
181
182
Georg Brandl01ba86a2008-11-06 10:20:49 +0000183.. _thread-objects:
184
185Thread Objects
186--------------
187
188This class represents an activity that is run in a separate thread of control.
189There are two ways to specify the activity: by passing a callable object to the
190constructor, or by overriding the :meth:`run` method in a subclass. No other
191methods (except for the constructor) should be overridden in a subclass. In
192other words, *only* override the :meth:`__init__` and :meth:`run` methods of
193this class.
194
195Once a thread object is created, its activity must be started by calling the
196thread's :meth:`start` method. This invokes the :meth:`run` method in a
197separate thread of control.
198
199Once the thread's activity is started, the thread is considered 'alive'. It
200stops being alive when its :meth:`run` method terminates -- either normally, or
201by raising an unhandled exception. The :meth:`is_alive` method tests whether the
202thread is alive.
203
204Other threads can call a thread's :meth:`join` method. This blocks the calling
205thread until the thread whose :meth:`join` method is called is terminated.
206
207A thread has a name. The name can be passed to the constructor, and read or
208changed through the :attr:`name` attribute.
209
210A thread can be flagged as a "daemon thread". The significance of this flag is
211that the entire Python program exits when only daemon threads are left. The
212initial value is inherited from the creating thread. The flag can be set
Georg Brandlecd2afa2009-02-05 11:40:35 +0000213through the :attr:`daemon` property.
Georg Brandl01ba86a2008-11-06 10:20:49 +0000214
215There is a "main thread" object; this corresponds to the initial thread of
216control in the Python program. It is not a daemon thread.
217
218There is the possibility that "dummy thread objects" are created. These are
219thread objects corresponding to "alien threads", which are threads of control
220started outside the threading module, such as directly from C code. Dummy
221thread objects have limited functionality; they are always considered alive and
222daemonic, and cannot be :meth:`join`\ ed. They are never deleted, since it is
223impossible to detect the termination of alien threads.
224
225
226.. class:: Thread(group=None, target=None, name=None, args=(), kwargs={})
227
228 This constructor should always be called with keyword arguments. Arguments are:
229
230 *group* should be ``None``; reserved for future extension when a
231 :class:`ThreadGroup` class is implemented.
232
233 *target* is the callable object to be invoked by the :meth:`run` method.
234 Defaults to ``None``, meaning nothing is called.
235
236 *name* is the thread name. By default, a unique name is constructed of the form
237 "Thread-*N*" where *N* is a small decimal number.
238
239 *args* is the argument tuple for the target invocation. Defaults to ``()``.
240
241 *kwargs* is a dictionary of keyword arguments for the target invocation.
242 Defaults to ``{}``.
243
244 If the subclass overrides the constructor, it must make sure to invoke the base
245 class constructor (``Thread.__init__()``) before doing anything else to the
246 thread.
247
248
249.. method:: Thread.start()
250
251 Start the thread's activity.
252
253 It must be called at most once per thread object. It arranges for the object's
254 :meth:`run` method to be invoked in a separate thread of control.
255
256 This method will raise a :exc:`RuntimeException` if called more than once on the
257 same thread object.
258
259
260.. method:: Thread.run()
261
262 Method representing the thread's activity.
263
264 You may override this method in a subclass. The standard :meth:`run` method
265 invokes the callable object passed to the object's constructor as the *target*
266 argument, if any, with sequential and keyword arguments taken from the *args*
267 and *kwargs* arguments, respectively.
268
269
270.. method:: Thread.join([timeout])
271
272 Wait until the thread terminates. This blocks the calling thread until the
273 thread whose :meth:`join` method is called terminates -- either normally or
274 through an unhandled exception -- or until the optional timeout occurs.
275
276 When the *timeout* argument is present and not ``None``, it should be a floating
277 point number specifying a timeout for the operation in seconds (or fractions
278 thereof). As :meth:`join` always returns ``None``, you must call :meth:`isAlive`
279 after :meth:`join` to decide whether a timeout happened -- if the thread is
280 still alive, the :meth:`join` call timed out.
281
282 When the *timeout* argument is not present or ``None``, the operation will block
283 until the thread terminates.
284
285 A thread can be :meth:`join`\ ed many times.
286
287 :meth:`join` raises a :exc:`RuntimeError` if an attempt is made to join
288 the current thread as that would cause a deadlock. It is also an error to
289 :meth:`join` a thread before it has been started and attempts to do so
290 raises the same exception.
291
292
293.. method:: Thread.getName()
294 Thread.setName()
295
296 Old API for :attr:`~Thread.name`.
297
298
299.. attribute:: Thread.name
300
301 A string used for identification purposes only. It has no semantics.
302 Multiple threads may be given the same name. The initial name is set by the
303 constructor.
304
305
306.. attribute:: Thread.ident
307
308 The 'thread identifier' of this thread or ``None`` if the thread has not been
309 started. This is a nonzero integer. See the :func:`thread.get_ident()`
310 function. Thread identifiers may be recycled when a thread exits and another
311 thread is created. The identifier is available even after the thread has
312 exited.
313
314 .. versionadded:: 2.6
315
316
317.. method:: Thread.is_alive()
318 Thread.isAlive()
319
320 Return whether the thread is alive.
321
322 Roughly, a thread is alive from the moment the :meth:`start` method returns
323 until its :meth:`run` method terminates. The module function :func:`enumerate`
324 returns a list of all alive threads.
325
326
327.. method:: Thread.isDaemon()
328 Thread.setDaemon()
329
330 Old API for :attr:`~Thread.daemon`.
331
332
333.. attribute:: Thread.daemon
334
Georg Brandlecd2afa2009-02-05 11:40:35 +0000335 A boolean value indicating whether this thread is a daemon thread (True) or
336 not (False). This must be set before :meth:`start` is called, otherwise
337 :exc:`RuntimeError` is raised. Its initial value is inherited from the
338 creating thread; the main thread is not a daemon thread and therefore all
339 threads created in the main thread default to :attr:`daemon` = ``False``.
Georg Brandl01ba86a2008-11-06 10:20:49 +0000340
341 The entire Python program exits when no alive non-daemon threads are left.
342
343
Georg Brandl8ec7f652007-08-15 14:28:01 +0000344.. _lock-objects:
345
346Lock Objects
347------------
348
349A primitive lock is a synchronization primitive that is not owned by a
350particular thread when locked. In Python, it is currently the lowest level
351synchronization primitive available, implemented directly by the :mod:`thread`
352extension module.
353
354A primitive lock is in one of two states, "locked" or "unlocked". It is created
355in the unlocked state. It has two basic methods, :meth:`acquire` and
356:meth:`release`. When the state is unlocked, :meth:`acquire` changes the state
357to locked and returns immediately. When the state is locked, :meth:`acquire`
358blocks until a call to :meth:`release` in another thread changes it to unlocked,
359then the :meth:`acquire` call resets it to locked and returns. The
360:meth:`release` method should only be called in the locked state; it changes the
361state to unlocked and returns immediately. If an attempt is made to release an
362unlocked lock, a :exc:`RuntimeError` will be raised.
363
364When more than one thread is blocked in :meth:`acquire` waiting for the state to
365turn to unlocked, only one thread proceeds when a :meth:`release` call resets
366the state to unlocked; which one of the waiting threads proceeds is not defined,
367and may vary across implementations.
368
369All methods are executed atomically.
370
371
372.. method:: Lock.acquire([blocking=1])
373
374 Acquire a lock, blocking or non-blocking.
375
376 When invoked without arguments, block until the lock is unlocked, then set it to
377 locked, and return true.
378
379 When invoked with the *blocking* argument set to true, do the same thing as when
380 called without arguments, and return true.
381
382 When invoked with the *blocking* argument set to false, do not block. If a call
383 without an argument would block, return false immediately; otherwise, do the
384 same thing as when called without arguments, and return true.
385
386
387.. method:: Lock.release()
388
389 Release a lock.
390
391 When the lock is locked, reset it to unlocked, and return. If any other threads
392 are blocked waiting for the lock to become unlocked, allow exactly one of them
393 to proceed.
394
395 Do not call this method when the lock is unlocked.
396
397 There is no return value.
398
399
400.. _rlock-objects:
401
402RLock Objects
403-------------
404
405A reentrant lock is a synchronization primitive that may be acquired multiple
406times by the same thread. Internally, it uses the concepts of "owning thread"
407and "recursion level" in addition to the locked/unlocked state used by primitive
408locks. In the locked state, some thread owns the lock; in the unlocked state,
409no thread owns it.
410
411To lock the lock, a thread calls its :meth:`acquire` method; this returns once
412the thread owns the lock. To unlock the lock, a thread calls its
413:meth:`release` method. :meth:`acquire`/:meth:`release` call pairs may be
414nested; only the final :meth:`release` (the :meth:`release` of the outermost
415pair) resets the lock to unlocked and allows another thread blocked in
416:meth:`acquire` to proceed.
417
418
419.. method:: RLock.acquire([blocking=1])
420
421 Acquire a lock, blocking or non-blocking.
422
423 When invoked without arguments: if this thread already owns the lock, increment
424 the recursion level by one, and return immediately. Otherwise, if another
425 thread owns the lock, block until the lock is unlocked. Once the lock is
426 unlocked (not owned by any thread), then grab ownership, set the recursion level
427 to one, and return. If more than one thread is blocked waiting until the lock
428 is unlocked, only one at a time will be able to grab ownership of the lock.
429 There is no return value in this case.
430
431 When invoked with the *blocking* argument set to true, do the same thing as when
432 called without arguments, and return true.
433
434 When invoked with the *blocking* argument set to false, do not block. If a call
435 without an argument would block, return false immediately; otherwise, do the
436 same thing as when called without arguments, and return true.
437
438
439.. method:: RLock.release()
440
441 Release a lock, decrementing the recursion level. If after the decrement it is
442 zero, reset the lock to unlocked (not owned by any thread), and if any other
443 threads are blocked waiting for the lock to become unlocked, allow exactly one
444 of them to proceed. If after the decrement the recursion level is still
445 nonzero, the lock remains locked and owned by the calling thread.
446
447 Only call this method when the calling thread owns the lock. A
448 :exc:`RuntimeError` is raised if this method is called when the lock is
449 unlocked.
450
451 There is no return value.
452
453
454.. _condition-objects:
455
456Condition Objects
457-----------------
458
459A condition variable is always associated with some kind of lock; this can be
460passed in or one will be created by default. (Passing one in is useful when
461several condition variables must share the same lock.)
462
463A condition variable has :meth:`acquire` and :meth:`release` methods that call
464the corresponding methods of the associated lock. It also has a :meth:`wait`
465method, and :meth:`notify` and :meth:`notifyAll` methods. These three must only
466be called when the calling thread has acquired the lock, otherwise a
467:exc:`RuntimeError` is raised.
468
469The :meth:`wait` method releases the lock, and then blocks until it is awakened
470by a :meth:`notify` or :meth:`notifyAll` call for the same condition variable in
471another thread. Once awakened, it re-acquires the lock and returns. It is also
472possible to specify a timeout.
473
474The :meth:`notify` method wakes up one of the threads waiting for the condition
475variable, if any are waiting. The :meth:`notifyAll` method wakes up all threads
476waiting for the condition variable.
477
478Note: the :meth:`notify` and :meth:`notifyAll` methods don't release the lock;
479this means that the thread or threads awakened will not return from their
480:meth:`wait` call immediately, but only when the thread that called
481:meth:`notify` or :meth:`notifyAll` finally relinquishes ownership of the lock.
482
483Tip: the typical programming style using condition variables uses the lock to
484synchronize access to some shared state; threads that are interested in a
485particular change of state call :meth:`wait` repeatedly until they see the
486desired state, while threads that modify the state call :meth:`notify` or
487:meth:`notifyAll` when they change the state in such a way that it could
488possibly be a desired state for one of the waiters. For example, the following
489code is a generic producer-consumer situation with unlimited buffer capacity::
490
491 # Consume one item
492 cv.acquire()
493 while not an_item_is_available():
494 cv.wait()
495 get_an_available_item()
496 cv.release()
497
498 # Produce one item
499 cv.acquire()
500 make_an_item_available()
501 cv.notify()
502 cv.release()
503
504To choose between :meth:`notify` and :meth:`notifyAll`, consider whether one
505state change can be interesting for only one or several waiting threads. E.g.
506in a typical producer-consumer situation, adding one item to the buffer only
507needs to wake up one consumer thread.
508
509
510.. class:: Condition([lock])
511
512 If the *lock* argument is given and not ``None``, it must be a :class:`Lock` or
513 :class:`RLock` object, and it is used as the underlying lock. Otherwise, a new
514 :class:`RLock` object is created and used as the underlying lock.
515
516
517.. method:: Condition.acquire(*args)
518
519 Acquire the underlying lock. This method calls the corresponding method on the
520 underlying lock; the return value is whatever that method returns.
521
522
523.. method:: Condition.release()
524
525 Release the underlying lock. This method calls the corresponding method on the
526 underlying lock; there is no return value.
527
528
529.. method:: Condition.wait([timeout])
530
531 Wait until notified or until a timeout occurs. If the calling thread has not
532 acquired the lock when this method is called, a :exc:`RuntimeError` is raised.
533
534 This method releases the underlying lock, and then blocks until it is awakened
535 by a :meth:`notify` or :meth:`notifyAll` call for the same condition variable in
536 another thread, or until the optional timeout occurs. Once awakened or timed
537 out, it re-acquires the lock and returns.
538
539 When the *timeout* argument is present and not ``None``, it should be a floating
540 point number specifying a timeout for the operation in seconds (or fractions
541 thereof).
542
543 When the underlying lock is an :class:`RLock`, it is not released using its
544 :meth:`release` method, since this may not actually unlock the lock when it was
545 acquired multiple times recursively. Instead, an internal interface of the
546 :class:`RLock` class is used, which really unlocks it even when it has been
547 recursively acquired several times. Another internal interface is then used to
548 restore the recursion level when the lock is reacquired.
549
550
551.. method:: Condition.notify()
552
553 Wake up a thread waiting on this condition, if any. Wait until notified or until
554 a timeout occurs. If the calling thread has not acquired the lock when this
555 method is called, a :exc:`RuntimeError` is raised.
556
557 This method wakes up one of the threads waiting for the condition variable, if
558 any are waiting; it is a no-op if no threads are waiting.
559
560 The current implementation wakes up exactly one thread, if any are waiting.
561 However, it's not safe to rely on this behavior. A future, optimized
562 implementation may occasionally wake up more than one thread.
563
564 Note: the awakened thread does not actually return from its :meth:`wait` call
565 until it can reacquire the lock. Since :meth:`notify` does not release the
566 lock, its caller should.
567
568
Benjamin Peterson0fbcf692008-06-11 17:27:50 +0000569.. method:: Condition.notify_all()
Benjamin Petersonf4395602008-06-11 17:50:00 +0000570 Condition.notifyAll()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000571
572 Wake up all threads waiting on this condition. This method acts like
573 :meth:`notify`, but wakes up all waiting threads instead of one. If the calling
574 thread has not acquired the lock when this method is called, a
575 :exc:`RuntimeError` is raised.
576
577
578.. _semaphore-objects:
579
580Semaphore Objects
581-----------------
582
583This is one of the oldest synchronization primitives in the history of computer
584science, invented by the early Dutch computer scientist Edsger W. Dijkstra (he
585used :meth:`P` and :meth:`V` instead of :meth:`acquire` and :meth:`release`).
586
587A semaphore manages an internal counter which is decremented by each
588:meth:`acquire` call and incremented by each :meth:`release` call. The counter
589can never go below zero; when :meth:`acquire` finds that it is zero, it blocks,
590waiting until some other thread calls :meth:`release`.
591
592
593.. class:: Semaphore([value])
594
595 The optional argument gives the initial *value* for the internal counter; it
596 defaults to ``1``. If the *value* given is less than 0, :exc:`ValueError` is
597 raised.
598
599
600.. method:: Semaphore.acquire([blocking])
601
602 Acquire a semaphore.
603
604 When invoked without arguments: if the internal counter is larger than zero on
605 entry, decrement it by one and return immediately. If it is zero on entry,
606 block, waiting until some other thread has called :meth:`release` to make it
607 larger than zero. This is done with proper interlocking so that if multiple
608 :meth:`acquire` calls are blocked, :meth:`release` will wake exactly one of them
609 up. The implementation may pick one at random, so the order in which blocked
610 threads are awakened should not be relied on. There is no return value in this
611 case.
612
613 When invoked with *blocking* set to true, do the same thing as when called
614 without arguments, and return true.
615
616 When invoked with *blocking* set to false, do not block. If a call without an
617 argument would block, return false immediately; otherwise, do the same thing as
618 when called without arguments, and return true.
619
620
621.. method:: Semaphore.release()
622
623 Release a semaphore, incrementing the internal counter by one. When it was zero
624 on entry and another thread is waiting for it to become larger than zero again,
625 wake up that thread.
626
627
628.. _semaphore-examples:
629
630:class:`Semaphore` Example
631^^^^^^^^^^^^^^^^^^^^^^^^^^
632
633Semaphores are often used to guard resources with limited capacity, for example,
634a database server. In any situation where the size of the resource size is
635fixed, you should use a bounded semaphore. Before spawning any worker threads,
636your main thread would initialize the semaphore::
637
638 maxconnections = 5
639 ...
640 pool_sema = BoundedSemaphore(value=maxconnections)
641
642Once spawned, worker threads call the semaphore's acquire and release methods
643when they need to connect to the server::
644
645 pool_sema.acquire()
646 conn = connectdb()
647 ... use connection ...
648 conn.close()
649 pool_sema.release()
650
651The use of a bounded semaphore reduces the chance that a programming error which
652causes the semaphore to be released more than it's acquired will go undetected.
653
654
655.. _event-objects:
656
657Event Objects
658-------------
659
660This is one of the simplest mechanisms for communication between threads: one
661thread signals an event and other threads wait for it.
662
663An event object manages an internal flag that can be set to true with the
664:meth:`set` method and reset to false with the :meth:`clear` method. The
665:meth:`wait` method blocks until the flag is true.
666
667
668.. class:: Event()
669
670 The internal flag is initially false.
671
672
Benjamin Petersonf4395602008-06-11 17:50:00 +0000673.. method:: Event.is_set()
674 Event.isSet()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000675
676 Return true if and only if the internal flag is true.
677
678
679.. method:: Event.set()
680
681 Set the internal flag to true. All threads waiting for it to become true are
682 awakened. Threads that call :meth:`wait` once the flag is true will not block at
683 all.
684
685
686.. method:: Event.clear()
687
688 Reset the internal flag to false. Subsequently, threads calling :meth:`wait`
689 will block until :meth:`set` is called to set the internal flag to true again.
690
691
692.. method:: Event.wait([timeout])
693
694 Block until the internal flag is true. If the internal flag is true on entry,
695 return immediately. Otherwise, block until another thread calls :meth:`set` to
696 set the flag to true, or until the optional timeout occurs.
697
698 When the timeout argument is present and not ``None``, it should be a floating
699 point number specifying a timeout for the operation in seconds (or fractions
700 thereof).
701
702
Georg Brandl8ec7f652007-08-15 14:28:01 +0000703.. _timer-objects:
704
705Timer Objects
706-------------
707
708This class represents an action that should be run only after a certain amount
709of time has passed --- a timer. :class:`Timer` is a subclass of :class:`Thread`
710and as such also functions as an example of creating custom threads.
711
712Timers are started, as with threads, by calling their :meth:`start` method. The
713timer can be stopped (before its action has begun) by calling the :meth:`cancel`
714method. The interval the timer will wait before executing its action may not be
715exactly the same as the interval specified by the user.
716
717For example::
718
719 def hello():
720 print "hello, world"
721
722 t = Timer(30.0, hello)
723 t.start() # after 30 seconds, "hello, world" will be printed
724
725
726.. class:: Timer(interval, function, args=[], kwargs={})
727
728 Create a timer that will run *function* with arguments *args* and keyword
729 arguments *kwargs*, after *interval* seconds have passed.
730
731
732.. method:: Timer.cancel()
733
734 Stop the timer, and cancel the execution of the timer's action. This will only
735 work if the timer is still in its waiting stage.
736
737
738.. _with-locks:
739
740Using locks, conditions, and semaphores in the :keyword:`with` statement
741------------------------------------------------------------------------
742
743All of the objects provided by this module that have :meth:`acquire` and
744:meth:`release` methods can be used as context managers for a :keyword:`with`
745statement. The :meth:`acquire` method will be called when the block is entered,
746and :meth:`release` will be called when the block is exited.
747
748Currently, :class:`Lock`, :class:`RLock`, :class:`Condition`,
749:class:`Semaphore`, and :class:`BoundedSemaphore` objects may be used as
750:keyword:`with` statement context managers. For example::
751
Georg Brandl8ec7f652007-08-15 14:28:01 +0000752 import threading
753
754 some_rlock = threading.RLock()
755
756 with some_rlock:
757 print "some_rlock is locked while this executes"
758
Georg Brandl2e255512008-03-13 07:21:41 +0000759
760.. _threaded-imports:
761
762Importing in threaded code
763--------------------------
764
765While the import machinery is thread safe, there are two key
766restrictions on threaded imports due to inherent limitations in the way
767that thread safety is provided:
768
769* Firstly, other than in the main module, an import should not have the
770 side effect of spawning a new thread and then waiting for that thread in
771 any way. Failing to abide by this restriction can lead to a deadlock if
772 the spawned thread directly or indirectly attempts to import a module.
773* Secondly, all import attempts must be completed before the interpreter
774 starts shutting itself down. This can be most easily achieved by only
775 performing imports from non-daemon threads created through the threading
776 module. Daemon threads and threads created directly with the thread
777 module will require some other form of synchronization to ensure they do
778 not attempt imports after system shutdown has commenced. Failure to
779 abide by this restriction will lead to intermittent exceptions and
780 crashes during interpreter shutdown (as the late imports attempt to
781 access machinery which is no longer in a valid state).