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