/Doc/library/thread.rst

http://unladen-swallow.googlecode.com/ · ReStructuredText · 178 lines · 118 code · 60 blank · 0 comment · 0 complexity · 0a27e3d94aa702e34e3f871fbe960497 MD5 · raw file

  1. :mod:`thread` --- Multiple threads of control
  2. =============================================
  3. .. module:: thread
  4. :synopsis: Create multiple threads of control within one interpreter.
  5. .. note::
  6. The :mod:`thread` module has been renamed to :mod:`_thread` in Python 3.0.
  7. The :term:`2to3` tool will automatically adapt imports when converting your
  8. sources to 3.0; however, you should consider using the high-level
  9. :mod:`threading` module instead.
  10. .. index::
  11. single: light-weight processes
  12. single: processes, light-weight
  13. single: binary semaphores
  14. single: semaphores, binary
  15. This module provides low-level primitives for working with multiple threads
  16. (also called :dfn:`light-weight processes` or :dfn:`tasks`) --- multiple threads of
  17. control sharing their global data space. For synchronization, simple locks
  18. (also called :dfn:`mutexes` or :dfn:`binary semaphores`) are provided.
  19. The :mod:`threading` module provides an easier to use and higher-level
  20. threading API built on top of this module.
  21. .. index::
  22. single: pthreads
  23. pair: threads; POSIX
  24. The module is optional. It is supported on Windows, Linux, SGI IRIX, Solaris
  25. 2.x, as well as on systems that have a POSIX thread (a.k.a. "pthread")
  26. implementation. For systems lacking the :mod:`thread` module, the
  27. :mod:`dummy_thread` module is available. It duplicates this module's interface
  28. and can be used as a drop-in replacement.
  29. It defines the following constant and functions:
  30. .. exception:: error
  31. Raised on thread-specific errors.
  32. .. data:: LockType
  33. This is the type of lock objects.
  34. .. function:: start_new_thread(function, args[, kwargs])
  35. Start a new thread and return its identifier. The thread executes the function
  36. *function* with the argument list *args* (which must be a tuple). The optional
  37. *kwargs* argument specifies a dictionary of keyword arguments. When the function
  38. returns, the thread silently exits. When the function terminates with an
  39. unhandled exception, a stack trace is printed and then the thread exits (but
  40. other threads continue to run).
  41. .. function:: interrupt_main()
  42. Raise a :exc:`KeyboardInterrupt` exception in the main thread. A subthread can
  43. use this function to interrupt the main thread.
  44. .. versionadded:: 2.3
  45. .. function:: exit()
  46. Raise the :exc:`SystemExit` exception. When not caught, this will cause the
  47. thread to exit silently.
  48. ..
  49. function:: exit_prog(status)
  50. Exit all threads and report the value of the integer argument
  51. *status* as the exit status of the entire program.
  52. **Caveat:** code in pending :keyword:`finally` clauses, in this thread
  53. or in other threads, is not executed.
  54. .. function:: allocate_lock()
  55. Return a new lock object. Methods of locks are described below. The lock is
  56. initially unlocked.
  57. .. function:: get_ident()
  58. Return the 'thread identifier' of the current thread. This is a nonzero
  59. integer. Its value has no direct meaning; it is intended as a magic cookie to
  60. be used e.g. to index a dictionary of thread-specific data. Thread identifiers
  61. may be recycled when a thread exits and another thread is created.
  62. .. function:: stack_size([size])
  63. Return the thread stack size used when creating new threads. The optional
  64. *size* argument specifies the stack size to be used for subsequently created
  65. threads, and must be 0 (use platform or configured default) or a positive
  66. integer value of at least 32,768 (32kB). If changing the thread stack size is
  67. unsupported, the :exc:`error` exception is raised. If the specified stack size is
  68. invalid, a :exc:`ValueError` is raised and the stack size is unmodified. 32kB
  69. is currently the minimum supported stack size value to guarantee sufficient
  70. stack space for the interpreter itself. Note that some platforms may have
  71. particular restrictions on values for the stack size, such as requiring a
  72. minimum stack size > 32kB or requiring allocation in multiples of the system
  73. memory page size - platform documentation should be referred to for more
  74. information (4kB pages are common; using multiples of 4096 for the stack size is
  75. the suggested approach in the absence of more specific information).
  76. Availability: Windows, systems with POSIX threads.
  77. .. versionadded:: 2.5
  78. Lock objects have the following methods:
  79. .. method:: lock.acquire([waitflag])
  80. Without the optional argument, this method acquires the lock unconditionally, if
  81. necessary waiting until it is released by another thread (only one thread at a
  82. time can acquire a lock --- that's their reason for existence). If the integer
  83. *waitflag* argument is present, the action depends on its value: if it is zero,
  84. the lock is only acquired if it can be acquired immediately without waiting,
  85. while if it is nonzero, the lock is acquired unconditionally as before. The
  86. return value is ``True`` if the lock is acquired successfully, ``False`` if not.
  87. .. method:: lock.release()
  88. Releases the lock. The lock must have been acquired earlier, but not
  89. necessarily by the same thread.
  90. .. method:: lock.locked()
  91. Return the status of the lock: ``True`` if it has been acquired by some thread,
  92. ``False`` if not.
  93. In addition to these methods, lock objects can also be used via the
  94. :keyword:`with` statement, e.g.::
  95. import thread
  96. a_lock = thread.allocate_lock()
  97. with a_lock:
  98. print "a_lock is locked while this executes"
  99. **Caveats:**
  100. .. index:: module: signal
  101. * Threads interact strangely with interrupts: the :exc:`KeyboardInterrupt`
  102. exception will be received by an arbitrary thread. (When the :mod:`signal`
  103. module is available, interrupts always go to the main thread.)
  104. * Calling :func:`sys.exit` or raising the :exc:`SystemExit` exception is
  105. equivalent to calling :func:`exit`.
  106. * Not all built-in functions that may block waiting for I/O allow other threads
  107. to run. (The most popular ones (:func:`time.sleep`, :meth:`file.read`,
  108. :func:`select.select`) work as expected.)
  109. * It is not possible to interrupt the :meth:`acquire` method on a lock --- the
  110. :exc:`KeyboardInterrupt` exception will happen after the lock has been acquired.
  111. .. index:: pair: threads; IRIX
  112. * When the main thread exits, it is system defined whether the other threads
  113. survive. On SGI IRIX using the native thread implementation, they survive. On
  114. most other systems, they are killed without executing :keyword:`try` ...
  115. :keyword:`finally` clauses or executing object destructors.
  116. * When the main thread exits, it does not do any of its usual cleanup (except
  117. that :keyword:`try` ... :keyword:`finally` clauses are honored), and the
  118. standard I/O files are not flushed.