threading
Python(CPython) 提供了 _thread 和 threading 两个线程模块,_thread 是低级模块,threading 对 _thread 进行了封装,提高了 _thread 原有功能的易用性以及扩展了新功能,通常我们只需要使用 threading 模块就可以了,这里我们也只对 threading 模块进行详细介绍。
方法属性
首先,我们来看一下 threading
模块的直接方法和属性。
threading.enumerate()
以列表形式返回当前所有存活的 threading.Thread 对象。
threading.active_count()
返回当前存活的 threading.Thread 对象,等于 len(threading.enumerate())。
threading.current_thread()
返回当前对应调用者控制的 threading.Thread 对象,如果调用者的控制线程不是利用 threading 创建,则会返回一个功能受限的虚拟线程对象。
threading.get_ident()
返回当前线程的线程标识符,它是一个非零的整数,其值没有直接含义,它可能会在线程退出,新线程创建时被复用。
threading.main_thread()
返回主线程对象,一般情况下,主线程是 Python 解释器开始时创建的线程。
threading.stack_size([size])
返回创建线程时用的堆栈大小,可选参数 size 指定之后新建线程的堆栈大小,size 值需要为 0 或者最小是 32768(32KiB)的一个正整数,如不指定 size,则默认为 0。
threading.get_native_id()
返回内核分配给当前线程的原生集成线程 ID,其值是一个非负整数。
threading.TIMEOUT_MAX
指定阻塞函数(如:Lock.acquire(), Condition.wait() ...)中形参 timeout 允许的最大值,传入超过这个值的 timeout 会抛出 OverflowError 异常。