blob: 85860e5e404d98fddd3fa28bddb6c578793ef1c6 [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
213through the :attr:`daemon` attribute.
214
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
335 The thread's daemon flag. This must be set before :meth:`start` is called,
336 otherwise :exc:`RuntimeError` is raised.
337
338 The initial value is inherited from the creating thread.
339
340 The entire Python program exits when no alive non-daemon threads are left.
341
342
Georg Brandl8ec7f652007-08-15 14:28:01 +0000343.. _lock-objects:
344
345Lock Objects
346------------
347
348A primitive lock is a synchronization primitive that is not owned by a
349particular thread when locked. In Python, it is currently the lowest level
350synchronization primitive available, implemented directly by the :mod:`thread`
351extension module.
352
353A primitive lock is in one of two states, "locked" or "unlocked". It is created
354in the unlocked state. It has two basic methods, :meth:`acquire` and
355:meth:`release`. When the state is unlocked, :meth:`acquire` changes the state
356to locked and returns immediately. When the state is locked, :meth:`acquire`
357blocks until a call to :meth:`release` in another thread changes it to unlocked,
358then the :meth:`acquire` call resets it to locked and returns. The
359:meth:`release` method should only be called in the locked state; it changes the
360state to unlocked and returns immediately. If an attempt is made to release an
361unlocked lock, a :exc:`RuntimeError` will be raised.
362
363When more than one thread is blocked in :meth:`acquire` waiting for the state to
364turn to unlocked, only one thread proceeds when a :meth:`release` call resets
365the state to unlocked; which one of the waiting threads proceeds is not defined,
366and may vary across implementations.
367
368All methods are executed atomically.
369
370
371.. method:: Lock.acquire([blocking=1])
372
373 Acquire a lock, blocking or non-blocking.
374
375 When invoked without arguments, block until the lock is unlocked, then set it to
376 locked, and return true.
377
378 When invoked with the *blocking* argument set to true, do the same thing as when
379 called without arguments, and return true.
380
381 When invoked with the *blocking* argument set to false, do not block. If a call
382 without an argument would block, return false immediately; otherwise, do the
383 same thing as when called without arguments, and return true.
384
385
386.. method:: Lock.release()
387
388 Release a lock.
389
390 When the lock is locked, reset it to unlocked, and return. If any other threads
391 are blocked waiting for the lock to become unlocked, allow exactly one of them
392 to proceed.
393
394 Do not call this method when the lock is unlocked.
395
396 There is no return value.
397
398
399.. _rlock-objects:
400
401RLock Objects
402-------------
403
404A reentrant lock is a synchronization primitive that may be acquired multiple
405times by the same thread. Internally, it uses the concepts of "owning thread"
406and "recursion level" in addition to the locked/unlocked state used by primitive
407locks. In the locked state, some thread owns the lock; in the unlocked state,
408no thread owns it.
409
410To lock the lock, a thread calls its :meth:`acquire` method; this returns once
411the thread owns the lock. To unlock the lock, a thread calls its
412:meth:`release` method. :meth:`acquire`/:meth:`release` call pairs may be
413nested; only the final :meth:`release` (the :meth:`release` of the outermost
414pair) resets the lock to unlocked and allows another thread blocked in
415:meth:`acquire` to proceed.
416
417
418.. method:: RLock.acquire([blocking=1])
419
420 Acquire a lock, blocking or non-blocking.
421
422 When invoked without arguments: if this thread already owns the lock, increment
423 the recursion level by one, and return immediately. Otherwise, if another
424 thread owns the lock, block until the lock is unlocked. Once the lock is
425 unlocked (not owned by any thread), then grab ownership, set the recursion level
426 to one, and return. If more than one thread is blocked waiting until the lock
427 is unlocked, only one at a time will be able to grab ownership of the lock.
428 There is no return value in this case.
429
430 When invoked with the *blocking* argument set to true, do the same thing as when
431 called without arguments, and return true.
432
433 When invoked with the *blocking* argument set to false, do not block. If a call
434 without an argument would block, return false immediately; otherwise, do the
435 same thing as when called without arguments, and return true.
436
437
438.. method:: RLock.release()
439
440 Release a lock, decrementing the recursion level. If after the decrement it is
441 zero, reset the lock to unlocked (not owned by any thread), and if any other
442 threads are blocked waiting for the lock to become unlocked, allow exactly one
443 of them to proceed. If after the decrement the recursion level is still
444 nonzero, the lock remains locked and owned by the calling thread.
445
446 Only call this method when the calling thread owns the lock. A
447 :exc:`RuntimeError` is raised if this method is called when the lock is
448 unlocked.
449
450 There is no return value.
451
452
453.. _condition-objects:
454
455Condition Objects
456-----------------
457
458A condition variable is always associated with some kind of lock; this can be
459passed in or one will be created by default. (Passing one in is useful when
460several condition variables must share the same lock.)
461
462A condition variable has :meth:`acquire` and :meth:`release` methods that call
463the corresponding methods of the associated lock. It also has a :meth:`wait`
464method, and :meth:`notify` and :meth:`notifyAll` methods. These three must only
465be called when the calling thread has acquired the lock, otherwise a
466:exc:`RuntimeError` is raised.
467
468The :meth:`wait` method releases the lock, and then blocks until it is awakened
469by a :meth:`notify` or :meth:`notifyAll` call for the same condition variable in
470another thread. Once awakened, it re-acquires the lock and returns. It is also
471possible to specify a timeout.
472
473The :meth:`notify` method wakes up one of the threads waiting for the condition
474variable, if any are waiting. The :meth:`notifyAll` method wakes up all threads
475waiting for the condition variable.
476
477Note: the :meth:`notify` and :meth:`notifyAll` methods don't release the lock;
478this means that the thread or threads awakened will not return from their
479:meth:`wait` call immediately, but only when the thread that called
480:meth:`notify` or :meth:`notifyAll` finally relinquishes ownership of the lock.
481
482Tip: the typical programming style using condition variables uses the lock to
483synchronize access to some shared state; threads that are interested in a
484particular change of state call :meth:`wait` repeatedly until they see the
485desired state, while threads that modify the state call :meth:`notify` or
486:meth:`notifyAll` when they change the state in such a way that it could
487possibly be a desired state for one of the waiters. For example, the following
488code is a generic producer-consumer situation with unlimited buffer capacity::
489
490 # Consume one item
491 cv.acquire()
492 while not an_item_is_available():
493 cv.wait()
494 get_an_available_item()
495 cv.release()
496
497 # Produce one item
498 cv.acquire()
499 make_an_item_available()
500 cv.notify()
501 cv.release()
502
503To choose between :meth:`notify` and :meth:`notifyAll`, consider whether one
504state change can be interesting for only one or several waiting threads. E.g.
505in a typical producer-consumer situation, adding one item to the buffer only
506needs to wake up one consumer thread.
507
508
509.. class:: Condition([lock])
510
511 If the *lock* argument is given and not ``None``, it must be a :class:`Lock` or
512 :class:`RLock` object, and it is used as the underlying lock. Otherwise, a new
513 :class:`RLock` object is created and used as the underlying lock.
514
515
516.. method:: Condition.acquire(*args)
517
518 Acquire the underlying lock. This method calls the corresponding method on the
519 underlying lock; the return value is whatever that method returns.
520
521
522.. method:: Condition.release()
523
524 Release the underlying lock. This method calls the corresponding method on the
525 underlying lock; there is no return value.
526
527
528.. method:: Condition.wait([timeout])
529
530 Wait until notified or until a timeout occurs. If the calling thread has not
531 acquired the lock when this method is called, a :exc:`RuntimeError` is raised.
532
533 This method releases the underlying lock, and then blocks until it is awakened
534 by a :meth:`notify` or :meth:`notifyAll` call for the same condition variable in
535 another thread, or until the optional timeout occurs. Once awakened or timed
536 out, it re-acquires the lock and returns.
537
538 When the *timeout* argument is present and not ``None``, it should be a floating
539 point number specifying a timeout for the operation in seconds (or fractions
540 thereof).
541
542 When the underlying lock is an :class:`RLock`, it is not released using its
543 :meth:`release` method, since this may not actually unlock the lock when it was
544 acquired multiple times recursively. Instead, an internal interface of the
545 :class:`RLock` class is used, which really unlocks it even when it has been
546 recursively acquired several times. Another internal interface is then used to
547 restore the recursion level when the lock is reacquired.
548
549
550.. method:: Condition.notify()
551
552 Wake up a thread waiting on this condition, if any. Wait until notified or until
553 a timeout occurs. If the calling thread has not acquired the lock when this
554 method is called, a :exc:`RuntimeError` is raised.
555
556 This method wakes up one of the threads waiting for the condition variable, if
557 any are waiting; it is a no-op if no threads are waiting.
558
559 The current implementation wakes up exactly one thread, if any are waiting.
560 However, it's not safe to rely on this behavior. A future, optimized
561 implementation may occasionally wake up more than one thread.
562
563 Note: the awakened thread does not actually return from its :meth:`wait` call
564 until it can reacquire the lock. Since :meth:`notify` does not release the
565 lock, its caller should.
566
567
Benjamin Peterson0fbcf692008-06-11 17:27:50 +0000568.. method:: Condition.notify_all()
Benjamin Petersonf4395602008-06-11 17:50:00 +0000569 Condition.notifyAll()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000570
571 Wake up all threads waiting on this condition. This method acts like
572 :meth:`notify`, but wakes up all waiting threads instead of one. If the calling
573 thread has not acquired the lock when this method is called, a
574 :exc:`RuntimeError` is raised.
575
576
577.. _semaphore-objects:
578
579Semaphore Objects
580-----------------
581
582This is one of the oldest synchronization primitives in the history of computer
583science, invented by the early Dutch computer scientist Edsger W. Dijkstra (he
584used :meth:`P` and :meth:`V` instead of :meth:`acquire` and :meth:`release`).
585
586A semaphore manages an internal counter which is decremented by each
587:meth:`acquire` call and incremented by each :meth:`release` call. The counter
588can never go below zero; when :meth:`acquire` finds that it is zero, it blocks,
589waiting until some other thread calls :meth:`release`.
590
591
592.. class:: Semaphore([value])
593
594 The optional argument gives the initial *value* for the internal counter; it
595 defaults to ``1``. If the *value* given is less than 0, :exc:`ValueError` is
596 raised.
597
598
599.. method:: Semaphore.acquire([blocking])
600
601 Acquire a semaphore.
602
603 When invoked without arguments: if the internal counter is larger than zero on
604 entry, decrement it by one and return immediately. If it is zero on entry,
605 block, waiting until some other thread has called :meth:`release` to make it
606 larger than zero. This is done with proper interlocking so that if multiple
607 :meth:`acquire` calls are blocked, :meth:`release` will wake exactly one of them
608 up. The implementation may pick one at random, so the order in which blocked
609 threads are awakened should not be relied on. There is no return value in this
610 case.
611
612 When invoked with *blocking* set to true, do the same thing as when called
613 without arguments, and return true.
614
615 When invoked with *blocking* set to false, do not block. If a call without an
616 argument would block, return false immediately; otherwise, do the same thing as
617 when called without arguments, and return true.
618
619
620.. method:: Semaphore.release()
621
622 Release a semaphore, incrementing the internal counter by one. When it was zero
623 on entry and another thread is waiting for it to become larger than zero again,
624 wake up that thread.
625
626
627.. _semaphore-examples:
628
629:class:`Semaphore` Example
630^^^^^^^^^^^^^^^^^^^^^^^^^^
631
632Semaphores are often used to guard resources with limited capacity, for example,
633a database server. In any situation where the size of the resource size is
634fixed, you should use a bounded semaphore. Before spawning any worker threads,
635your main thread would initialize the semaphore::
636
637 maxconnections = 5
638 ...
639 pool_sema = BoundedSemaphore(value=maxconnections)
640
641Once spawned, worker threads call the semaphore's acquire and release methods
642when they need to connect to the server::
643
644 pool_sema.acquire()
645 conn = connectdb()
646 ... use connection ...
647 conn.close()
648 pool_sema.release()
649
650The use of a bounded semaphore reduces the chance that a programming error which
651causes the semaphore to be released more than it's acquired will go undetected.
652
653
654.. _event-objects:
655
656Event Objects
657-------------
658
659This is one of the simplest mechanisms for communication between threads: one
660thread signals an event and other threads wait for it.
661
662An event object manages an internal flag that can be set to true with the
663:meth:`set` method and reset to false with the :meth:`clear` method. The
664:meth:`wait` method blocks until the flag is true.
665
666
667.. class:: Event()
668
669 The internal flag is initially false.
670
671
Benjamin Petersonf4395602008-06-11 17:50:00 +0000672.. method:: Event.is_set()
673 Event.isSet()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000674
675 Return true if and only if the internal flag is true.
676
677
678.. method:: Event.set()
679
680 Set the internal flag to true. All threads waiting for it to become true are
681 awakened. Threads that call :meth:`wait` once the flag is true will not block at
682 all.
683
684
685.. method:: Event.clear()
686
687 Reset the internal flag to false. Subsequently, threads calling :meth:`wait`
688 will block until :meth:`set` is called to set the internal flag to true again.
689
690
691.. method:: Event.wait([timeout])
692
693 Block until the internal flag is true. If the internal flag is true on entry,
694 return immediately. Otherwise, block until another thread calls :meth:`set` to
695 set the flag to true, or until the optional timeout occurs.
696
697 When the timeout argument is present and not ``None``, it should be a floating
698 point number specifying a timeout for the operation in seconds (or fractions
699 thereof).
700
701
Georg Brandl8ec7f652007-08-15 14:28:01 +0000702.. _timer-objects:
703
704Timer Objects
705-------------
706
707This class represents an action that should be run only after a certain amount
708of time has passed --- a timer. :class:`Timer` is a subclass of :class:`Thread`
709and as such also functions as an example of creating custom threads.
710
711Timers are started, as with threads, by calling their :meth:`start` method. The
712timer can be stopped (before its action has begun) by calling the :meth:`cancel`
713method. The interval the timer will wait before executing its action may not be
714exactly the same as the interval specified by the user.
715
716For example::
717
718 def hello():
719 print "hello, world"
720
721 t = Timer(30.0, hello)
722 t.start() # after 30 seconds, "hello, world" will be printed
723
724
725.. class:: Timer(interval, function, args=[], kwargs={})
726
727 Create a timer that will run *function* with arguments *args* and keyword
728 arguments *kwargs*, after *interval* seconds have passed.
729
730
731.. method:: Timer.cancel()
732
733 Stop the timer, and cancel the execution of the timer's action. This will only
734 work if the timer is still in its waiting stage.
735
736
737.. _with-locks:
738
739Using locks, conditions, and semaphores in the :keyword:`with` statement
740------------------------------------------------------------------------
741
742All of the objects provided by this module that have :meth:`acquire` and
743:meth:`release` methods can be used as context managers for a :keyword:`with`
744statement. The :meth:`acquire` method will be called when the block is entered,
745and :meth:`release` will be called when the block is exited.
746
747Currently, :class:`Lock`, :class:`RLock`, :class:`Condition`,
748:class:`Semaphore`, and :class:`BoundedSemaphore` objects may be used as
749:keyword:`with` statement context managers. For example::
750
Georg Brandl8ec7f652007-08-15 14:28:01 +0000751 import threading
752
753 some_rlock = threading.RLock()
754
755 with some_rlock:
756 print "some_rlock is locked while this executes"
757
Georg Brandl2e255512008-03-13 07:21:41 +0000758
759.. _threaded-imports:
760
761Importing in threaded code
762--------------------------
763
764While the import machinery is thread safe, there are two key
765restrictions on threaded imports due to inherent limitations in the way
766that thread safety is provided:
767
768* Firstly, other than in the main module, an import should not have the
769 side effect of spawning a new thread and then waiting for that thread in
770 any way. Failing to abide by this restriction can lead to a deadlock if
771 the spawned thread directly or indirectly attempts to import a module.
772* Secondly, all import attempts must be completed before the interpreter
773 starts shutting itself down. This can be most easily achieved by only
774 performing imports from non-daemon threads created through the threading
775 module. Daemon threads and threads created directly with the thread
776 module will require some other form of synchronization to ensure they do
777 not attempt imports after system shutdown has commenced. Failure to
778 abide by this restriction will lead to intermittent exceptions and
779 crashes during interpreter shutdown (as the late imports attempt to
780 access machinery which is no longer in a valid state).