16.3. thread — 多线程控制

注意

The thread module has been renamed to _thread in Python 3. The 2to3 tool will automatically adapt imports when converting your sources to Python 3; however, you should consider using the high-level threading 模块代替。

此模块提供用于处理多个线程的低级原语 (也称 轻量进程 or tasks ) — 多个控制线程共享其全局数据空间。对于同步而言,简单锁 (也称 mutexes or 二进制信号量 ) 被提供。 threading 模块提供构建于此模块之上,更易于使用且更高级的线程 API。

The module is optional. It is supported on Windows, Linux, SGI IRIX, Solaris 2.x, as well as on systems that have a POSIX thread (a.k.a. “pthread”) implementation. For systems lacking the thread module, the dummy_thread module is available. It duplicates this module’s interface and can be used as a drop-in replacement.

It defines the following constant and functions:

exception thread. error

引发特定线程错误。

thread. LockType

这是锁对象的类型。

thread. start_new_thread ( function , args [ , kwargs ] )

启动新线程并返回其标识符。线程执行函数 function 采用自变量列表 args (其必须是元组)。可选 kwargs argument specifies a dictionary of keyword arguments. When the function returns, the thread silently exits. When the function terminates with an unhandled exception, a stack trace is printed and then the thread exits (but other threads continue to run).

thread. interrupt_main ( )

引发 KeyboardInterrupt exception in the main thread. A subthread can use this function to interrupt the main thread.

2.3 版新增。

thread. exit ( )

引发 SystemExit 异常。若未被捕获,这将导致线程默默退出。

thread. allocate_lock ( )

返回新的锁对象。锁方法的描述如下。锁最初是解锁的。

thread. get_ident ( )

返回当前线程的 "线程标识符"。这是非 0 整数。它的值没有直接意义;旨在作为魔法 Cookie 使用 (如:索引特定线程数据的字典)。线程标识符会被回收,当退出线程并创建另一线程时。

thread. stack_size ( [ size ] )

返回创建新线程时使用的线程堆栈大小。可选 size argument specifies the stack size to be used for subsequently created threads, and must be 0 (use platform or configured default) or a positive integer value of at least 32,768 (32kB). If changing the thread stack size is unsupported, the error exception is raised. If the specified stack size is invalid, a ValueError is raised and the stack size is unmodified. 32kB is currently the minimum supported stack size value to guarantee sufficient stack space for the interpreter itself. Note that some platforms may have particular restrictions on values for the stack size, such as requiring a minimum stack size > 32kB or requiring allocation in multiples of the system memory page size - platform documentation should be referred to for more information (4kB pages are common; using multiples of 4096 for the stack size is the suggested approach in the absence of more specific information). Availability: Windows, systems with POSIX threads.

2.5 版新增。

锁对象拥有下列方法:

lock. acquire ( [ waitflag ] )

Without the optional argument, this method acquires the lock unconditionally, if necessary waiting until it is released by another thread (only one thread at a time can acquire a lock — that’s their reason for existence). If the integer waitflag argument is present, the action depends on its value: if it is zero, the lock is only acquired if it can be acquired immediately without waiting, while if it is nonzero, the lock is acquired unconditionally as before. The return value is True 若成功获取锁, False 若不。

lock. release ( )

释放锁。锁必须之前已获得,但不必是由同一线程。

lock. locked ( )

返回锁的状态: True 若它被某些线程获得, False 若不。

除这些方法外,锁对象还可以用于 with 语句,如:

import thread
a_lock = thread.allocate_lock()
with a_lock:
    print "a_lock is locked while this executes"
					

告诫:

  • 线程与中断的交互很奇怪: KeyboardInterrupt 异常会被任意线程收到。(当 signal 模块可用,中断始终转到主线程)

  • 调用 sys.exit() 或引发 SystemExit 异常相当于调用 thread.exit() .

  • 它是不可能的,中断 acquire() 方法在锁 — KeyboardInterrupt 异常将在已获得锁之后发生。

  • When the main thread exits, it is system defined whether the other threads survive. On SGI IRIX using the native thread implementation, they survive. On most other systems, they are killed without executing try ... finally 子句或执行对象析构函数。

  • 当主线程退出时,通常不做任何清理 (除了 try ... finally 子句被承兑),且不刷新标准 I/O 文件。

上一话题

16.2. threading — 更高级的线程接口

下一话题

16.4. dummy_threading — 直接置换 threading 模块

本页