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