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