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