blob: 1a43be58f97d87d1fe9d59e41a3a375def68217a [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
183.. _lock-objects:
184
185Lock Objects
186------------
187
188A primitive lock is a synchronization primitive that is not owned by a
189particular thread when locked. In Python, it is currently the lowest level
190synchronization primitive available, implemented directly by the :mod:`thread`
191extension module.
192
193A primitive lock is in one of two states, "locked" or "unlocked". It is created
194in the unlocked state. It has two basic methods, :meth:`acquire` and
195:meth:`release`. When the state is unlocked, :meth:`acquire` changes the state
196to locked and returns immediately. When the state is locked, :meth:`acquire`
197blocks until a call to :meth:`release` in another thread changes it to unlocked,
198then the :meth:`acquire` call resets it to locked and returns. The
199:meth:`release` method should only be called in the locked state; it changes the
200state to unlocked and returns immediately. If an attempt is made to release an
201unlocked lock, a :exc:`RuntimeError` will be raised.
202
203When more than one thread is blocked in :meth:`acquire` waiting for the state to
204turn to unlocked, only one thread proceeds when a :meth:`release` call resets
205the state to unlocked; which one of the waiting threads proceeds is not defined,
206and may vary across implementations.
207
208All methods are executed atomically.
209
210
211.. method:: Lock.acquire([blocking=1])
212
213 Acquire a lock, blocking or non-blocking.
214
215 When invoked without arguments, block until the lock is unlocked, then set it to
216 locked, and return true.
217
218 When invoked with the *blocking* argument set to true, do the same thing as when
219 called without arguments, and return true.
220
221 When invoked with the *blocking* argument set to false, do not block. If a call
222 without an argument would block, return false immediately; otherwise, do the
223 same thing as when called without arguments, and return true.
224
225
226.. method:: Lock.release()
227
228 Release a lock.
229
230 When the lock is locked, reset it to unlocked, and return. If any other threads
231 are blocked waiting for the lock to become unlocked, allow exactly one of them
232 to proceed.
233
234 Do not call this method when the lock is unlocked.
235
236 There is no return value.
237
238
239.. _rlock-objects:
240
241RLock Objects
242-------------
243
244A reentrant lock is a synchronization primitive that may be acquired multiple
245times by the same thread. Internally, it uses the concepts of "owning thread"
246and "recursion level" in addition to the locked/unlocked state used by primitive
247locks. In the locked state, some thread owns the lock; in the unlocked state,
248no thread owns it.
249
250To lock the lock, a thread calls its :meth:`acquire` method; this returns once
251the thread owns the lock. To unlock the lock, a thread calls its
252:meth:`release` method. :meth:`acquire`/:meth:`release` call pairs may be
253nested; only the final :meth:`release` (the :meth:`release` of the outermost
254pair) resets the lock to unlocked and allows another thread blocked in
255:meth:`acquire` to proceed.
256
257
258.. method:: RLock.acquire([blocking=1])
259
260 Acquire a lock, blocking or non-blocking.
261
262 When invoked without arguments: if this thread already owns the lock, increment
263 the recursion level by one, and return immediately. Otherwise, if another
264 thread owns the lock, block until the lock is unlocked. Once the lock is
265 unlocked (not owned by any thread), then grab ownership, set the recursion level
266 to one, and return. If more than one thread is blocked waiting until the lock
267 is unlocked, only one at a time will be able to grab ownership of the lock.
268 There is no return value in this case.
269
270 When invoked with the *blocking* argument set to true, do the same thing as when
271 called without arguments, and return true.
272
273 When invoked with the *blocking* argument set to false, do not block. If a call
274 without an argument would block, return false immediately; otherwise, do the
275 same thing as when called without arguments, and return true.
276
277
278.. method:: RLock.release()
279
280 Release a lock, decrementing the recursion level. If after the decrement it is
281 zero, reset the lock to unlocked (not owned by any thread), and if any other
282 threads are blocked waiting for the lock to become unlocked, allow exactly one
283 of them to proceed. If after the decrement the recursion level is still
284 nonzero, the lock remains locked and owned by the calling thread.
285
286 Only call this method when the calling thread owns the lock. A
287 :exc:`RuntimeError` is raised if this method is called when the lock is
288 unlocked.
289
290 There is no return value.
291
292
293.. _condition-objects:
294
295Condition Objects
296-----------------
297
298A condition variable is always associated with some kind of lock; this can be
299passed in or one will be created by default. (Passing one in is useful when
300several condition variables must share the same lock.)
301
302A condition variable has :meth:`acquire` and :meth:`release` methods that call
303the corresponding methods of the associated lock. It also has a :meth:`wait`
304method, and :meth:`notify` and :meth:`notifyAll` methods. These three must only
305be called when the calling thread has acquired the lock, otherwise a
306:exc:`RuntimeError` is raised.
307
308The :meth:`wait` method releases the lock, and then blocks until it is awakened
309by a :meth:`notify` or :meth:`notifyAll` call for the same condition variable in
310another thread. Once awakened, it re-acquires the lock and returns. It is also
311possible to specify a timeout.
312
313The :meth:`notify` method wakes up one of the threads waiting for the condition
314variable, if any are waiting. The :meth:`notifyAll` method wakes up all threads
315waiting for the condition variable.
316
317Note: the :meth:`notify` and :meth:`notifyAll` methods don't release the lock;
318this means that the thread or threads awakened will not return from their
319:meth:`wait` call immediately, but only when the thread that called
320:meth:`notify` or :meth:`notifyAll` finally relinquishes ownership of the lock.
321
322Tip: the typical programming style using condition variables uses the lock to
323synchronize access to some shared state; threads that are interested in a
324particular change of state call :meth:`wait` repeatedly until they see the
325desired state, while threads that modify the state call :meth:`notify` or
326:meth:`notifyAll` when they change the state in such a way that it could
327possibly be a desired state for one of the waiters. For example, the following
328code is a generic producer-consumer situation with unlimited buffer capacity::
329
330 # Consume one item
331 cv.acquire()
332 while not an_item_is_available():
333 cv.wait()
334 get_an_available_item()
335 cv.release()
336
337 # Produce one item
338 cv.acquire()
339 make_an_item_available()
340 cv.notify()
341 cv.release()
342
343To choose between :meth:`notify` and :meth:`notifyAll`, consider whether one
344state change can be interesting for only one or several waiting threads. E.g.
345in a typical producer-consumer situation, adding one item to the buffer only
346needs to wake up one consumer thread.
347
348
349.. class:: Condition([lock])
350
351 If the *lock* argument is given and not ``None``, it must be a :class:`Lock` or
352 :class:`RLock` object, and it is used as the underlying lock. Otherwise, a new
353 :class:`RLock` object is created and used as the underlying lock.
354
355
356.. method:: Condition.acquire(*args)
357
358 Acquire the underlying lock. This method calls the corresponding method on the
359 underlying lock; the return value is whatever that method returns.
360
361
362.. method:: Condition.release()
363
364 Release the underlying lock. This method calls the corresponding method on the
365 underlying lock; there is no return value.
366
367
368.. method:: Condition.wait([timeout])
369
370 Wait until notified or until a timeout occurs. If the calling thread has not
371 acquired the lock when this method is called, a :exc:`RuntimeError` is raised.
372
373 This method releases the underlying lock, and then blocks until it is awakened
374 by a :meth:`notify` or :meth:`notifyAll` call for the same condition variable in
375 another thread, or until the optional timeout occurs. Once awakened or timed
376 out, it re-acquires the lock and returns.
377
378 When the *timeout* argument is present and not ``None``, it should be a floating
379 point number specifying a timeout for the operation in seconds (or fractions
380 thereof).
381
382 When the underlying lock is an :class:`RLock`, it is not released using its
383 :meth:`release` method, since this may not actually unlock the lock when it was
384 acquired multiple times recursively. Instead, an internal interface of the
385 :class:`RLock` class is used, which really unlocks it even when it has been
386 recursively acquired several times. Another internal interface is then used to
387 restore the recursion level when the lock is reacquired.
388
389
390.. method:: Condition.notify()
391
392 Wake up a thread waiting on this condition, if any. Wait until notified or until
393 a timeout occurs. If the calling thread has not acquired the lock when this
394 method is called, a :exc:`RuntimeError` is raised.
395
396 This method wakes up one of the threads waiting for the condition variable, if
397 any are waiting; it is a no-op if no threads are waiting.
398
399 The current implementation wakes up exactly one thread, if any are waiting.
400 However, it's not safe to rely on this behavior. A future, optimized
401 implementation may occasionally wake up more than one thread.
402
403 Note: the awakened thread does not actually return from its :meth:`wait` call
404 until it can reacquire the lock. Since :meth:`notify` does not release the
405 lock, its caller should.
406
407
Benjamin Peterson0fbcf692008-06-11 17:27:50 +0000408.. method:: Condition.notify_all()
Benjamin Petersonf4395602008-06-11 17:50:00 +0000409 Condition.notifyAll()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000410
411 Wake up all threads waiting on this condition. This method acts like
412 :meth:`notify`, but wakes up all waiting threads instead of one. If the calling
413 thread has not acquired the lock when this method is called, a
414 :exc:`RuntimeError` is raised.
415
416
417.. _semaphore-objects:
418
419Semaphore Objects
420-----------------
421
422This is one of the oldest synchronization primitives in the history of computer
423science, invented by the early Dutch computer scientist Edsger W. Dijkstra (he
424used :meth:`P` and :meth:`V` instead of :meth:`acquire` and :meth:`release`).
425
426A semaphore manages an internal counter which is decremented by each
427:meth:`acquire` call and incremented by each :meth:`release` call. The counter
428can never go below zero; when :meth:`acquire` finds that it is zero, it blocks,
429waiting until some other thread calls :meth:`release`.
430
431
432.. class:: Semaphore([value])
433
434 The optional argument gives the initial *value* for the internal counter; it
435 defaults to ``1``. If the *value* given is less than 0, :exc:`ValueError` is
436 raised.
437
438
439.. method:: Semaphore.acquire([blocking])
440
441 Acquire a semaphore.
442
443 When invoked without arguments: if the internal counter is larger than zero on
444 entry, decrement it by one and return immediately. If it is zero on entry,
445 block, waiting until some other thread has called :meth:`release` to make it
446 larger than zero. This is done with proper interlocking so that if multiple
447 :meth:`acquire` calls are blocked, :meth:`release` will wake exactly one of them
448 up. The implementation may pick one at random, so the order in which blocked
449 threads are awakened should not be relied on. There is no return value in this
450 case.
451
452 When invoked with *blocking* set to true, do the same thing as when called
453 without arguments, and return true.
454
455 When invoked with *blocking* set to false, do not block. If a call without an
456 argument would block, return false immediately; otherwise, do the same thing as
457 when called without arguments, and return true.
458
459
460.. method:: Semaphore.release()
461
462 Release a semaphore, incrementing the internal counter by one. When it was zero
463 on entry and another thread is waiting for it to become larger than zero again,
464 wake up that thread.
465
466
467.. _semaphore-examples:
468
469:class:`Semaphore` Example
470^^^^^^^^^^^^^^^^^^^^^^^^^^
471
472Semaphores are often used to guard resources with limited capacity, for example,
473a database server. In any situation where the size of the resource size is
474fixed, you should use a bounded semaphore. Before spawning any worker threads,
475your main thread would initialize the semaphore::
476
477 maxconnections = 5
478 ...
479 pool_sema = BoundedSemaphore(value=maxconnections)
480
481Once spawned, worker threads call the semaphore's acquire and release methods
482when they need to connect to the server::
483
484 pool_sema.acquire()
485 conn = connectdb()
486 ... use connection ...
487 conn.close()
488 pool_sema.release()
489
490The use of a bounded semaphore reduces the chance that a programming error which
491causes the semaphore to be released more than it's acquired will go undetected.
492
493
494.. _event-objects:
495
496Event Objects
497-------------
498
499This is one of the simplest mechanisms for communication between threads: one
500thread signals an event and other threads wait for it.
501
502An event object manages an internal flag that can be set to true with the
503:meth:`set` method and reset to false with the :meth:`clear` method. The
504:meth:`wait` method blocks until the flag is true.
505
506
507.. class:: Event()
508
509 The internal flag is initially false.
510
511
Benjamin Petersonf4395602008-06-11 17:50:00 +0000512.. method:: Event.is_set()
513 Event.isSet()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000514
515 Return true if and only if the internal flag is true.
516
517
518.. method:: Event.set()
519
520 Set the internal flag to true. All threads waiting for it to become true are
521 awakened. Threads that call :meth:`wait` once the flag is true will not block at
522 all.
523
524
525.. method:: Event.clear()
526
527 Reset the internal flag to false. Subsequently, threads calling :meth:`wait`
528 will block until :meth:`set` is called to set the internal flag to true again.
529
530
531.. method:: Event.wait([timeout])
532
533 Block until the internal flag is true. If the internal flag is true on entry,
534 return immediately. Otherwise, block until another thread calls :meth:`set` to
535 set the flag to true, or until the optional timeout occurs.
536
537 When the timeout argument is present and not ``None``, it should be a floating
538 point number specifying a timeout for the operation in seconds (or fractions
539 thereof).
540
541
542.. _thread-objects:
543
544Thread Objects
545--------------
546
547This class represents an activity that is run in a separate thread of control.
548There are two ways to specify the activity: by passing a callable object to the
549constructor, or by overriding the :meth:`run` method in a subclass. No other
550methods (except for the constructor) should be overridden in a subclass. In
551other words, *only* override the :meth:`__init__` and :meth:`run` methods of
552this class.
553
554Once a thread object is created, its activity must be started by calling the
555thread's :meth:`start` method. This invokes the :meth:`run` method in a
556separate thread of control.
557
558Once the thread's activity is started, the thread is considered 'alive'. It
559stops being alive when its :meth:`run` method terminates -- either normally, or
Benjamin Petersonfacdd6e2008-08-18 22:29:19 +0000560by raising an unhandled exception. The :meth:`is_alive` method tests whether the
Georg Brandl8ec7f652007-08-15 14:28:01 +0000561thread is alive.
562
563Other threads can call a thread's :meth:`join` method. This blocks the calling
564thread until the thread whose :meth:`join` method is called is terminated.
565
Benjamin Petersonfacdd6e2008-08-18 22:29:19 +0000566A thread has a name. The name can be passed to the constructor, and read or
567changed through the :attr:`name` attribute.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000568
569A thread can be flagged as a "daemon thread". The significance of this flag is
570that the entire Python program exits when only daemon threads are left. The
Benjamin Petersonfacdd6e2008-08-18 22:29:19 +0000571initial value is inherited from the creating thread. The flag can be set
572through the :attr:`daemon` attribute.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000573
574There is a "main thread" object; this corresponds to the initial thread of
575control in the Python program. It is not a daemon thread.
576
577There is the possibility that "dummy thread objects" are created. These are
578thread objects corresponding to "alien threads", which are threads of control
579started outside the threading module, such as directly from C code. Dummy
580thread objects have limited functionality; they are always considered alive and
581daemonic, and cannot be :meth:`join`\ ed. They are never deleted, since it is
582impossible to detect the termination of alien threads.
583
584
585.. class:: Thread(group=None, target=None, name=None, args=(), kwargs={})
586
587 This constructor should always be called with keyword arguments. Arguments are:
588
589 *group* should be ``None``; reserved for future extension when a
590 :class:`ThreadGroup` class is implemented.
591
592 *target* is the callable object to be invoked by the :meth:`run` method.
593 Defaults to ``None``, meaning nothing is called.
594
595 *name* is the thread name. By default, a unique name is constructed of the form
596 "Thread-*N*" where *N* is a small decimal number.
597
598 *args* is the argument tuple for the target invocation. Defaults to ``()``.
599
600 *kwargs* is a dictionary of keyword arguments for the target invocation.
601 Defaults to ``{}``.
602
603 If the subclass overrides the constructor, it must make sure to invoke the base
604 class constructor (``Thread.__init__()``) before doing anything else to the
605 thread.
606
607
608.. method:: Thread.start()
609
610 Start the thread's activity.
611
612 It must be called at most once per thread object. It arranges for the object's
613 :meth:`run` method to be invoked in a separate thread of control.
614
615 This method will raise a :exc:`RuntimeException` if called more than once on the
616 same thread object.
617
618
619.. method:: Thread.run()
620
621 Method representing the thread's activity.
622
623 You may override this method in a subclass. The standard :meth:`run` method
624 invokes the callable object passed to the object's constructor as the *target*
625 argument, if any, with sequential and keyword arguments taken from the *args*
626 and *kwargs* arguments, respectively.
627
628
629.. method:: Thread.join([timeout])
630
631 Wait until the thread terminates. This blocks the calling thread until the
632 thread whose :meth:`join` method is called terminates -- either normally or
633 through an unhandled exception -- or until the optional timeout occurs.
634
635 When the *timeout* argument is present and not ``None``, it should be a floating
636 point number specifying a timeout for the operation in seconds (or fractions
Georg Brandl6ebc5272008-01-19 17:38:53 +0000637 thereof). As :meth:`join` always returns ``None``, you must call :meth:`isAlive`
638 after :meth:`join` to decide whether a timeout happened -- if the thread is
639 still alive, the :meth:`join` call timed out.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000640
641 When the *timeout* argument is not present or ``None``, the operation will block
642 until the thread terminates.
643
644 A thread can be :meth:`join`\ ed many times.
645
Georg Brandl6ebc5272008-01-19 17:38:53 +0000646 :meth:`join` raises a :exc:`RuntimeError` if an attempt is made to join
647 the current thread as that would cause a deadlock. It is also an error to
648 :meth:`join` a thread before it has been started and attempts to do so
649 raises the same exception.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000650
651
Benjamin Petersonfacdd6e2008-08-18 22:29:19 +0000652.. method:: Thread.getName()
653 Thread.setName()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000654
Benjamin Petersonfacdd6e2008-08-18 22:29:19 +0000655 Old API for :attr:`~Thread.name`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000656
657
Benjamin Petersonfacdd6e2008-08-18 22:29:19 +0000658.. attribute:: Thread.name
Georg Brandl8ec7f652007-08-15 14:28:01 +0000659
Benjamin Petersonfacdd6e2008-08-18 22:29:19 +0000660 A string used for identification purposes only. It has no semantics.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000661 Multiple threads may be given the same name. The initial name is set by the
662 constructor.
663
664
Benjamin Petersond8a89722008-08-18 16:40:03 +0000665.. attribute:: Thread.ident
Gregory P. Smith8856dda2008-06-01 23:48:47 +0000666
Benjamin Petersond8a89722008-08-18 16:40:03 +0000667 The 'thread identifier' of this thread or ``None`` if the thread has not been
668 started. This is a nonzero integer. See the :func:`thread.get_ident()`
Benjamin Peterson0fbcf692008-06-11 17:27:50 +0000669 function. Thread identifiers may be recycled when a thread exits and another
Benjamin Petersond8a89722008-08-18 16:40:03 +0000670 thread is created. The identifier is available even after the thread has
Benjamin Peterson0fbcf692008-06-11 17:27:50 +0000671 exited.
Gregory P. Smith8856dda2008-06-01 23:48:47 +0000672
673 .. versionadded:: 2.6
674
675
Benjamin Peterson0fbcf692008-06-11 17:27:50 +0000676.. method:: Thread.is_alive()
Benjamin Petersonf4395602008-06-11 17:50:00 +0000677 Thread.isAlive()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000678
679 Return whether the thread is alive.
680
681 Roughly, a thread is alive from the moment the :meth:`start` method returns
682 until its :meth:`run` method terminates. The module function :func:`enumerate`
683 returns a list of all alive threads.
684
685
Benjamin Petersonfacdd6e2008-08-18 22:29:19 +0000686.. method:: Thread.isDaemon()
687 Thread.setDaemon()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000688
Benjamin Petersonfacdd6e2008-08-18 22:29:19 +0000689 Old API for :attr:`~Thread.daemon`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000690
691
Benjamin Petersonfacdd6e2008-08-18 22:29:19 +0000692.. attribute:: Thread.daemon
Georg Brandl8ec7f652007-08-15 14:28:01 +0000693
Benjamin Petersonfacdd6e2008-08-18 22:29:19 +0000694 The thread's daemon flag. This must be set before :meth:`start` is called,
695 otherwise :exc:`RuntimeError` is raised.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000696
697 The initial value is inherited from the creating thread.
698
699 The entire Python program exits when no alive non-daemon threads are left.
700
701
702.. _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).