Threading Module源码概述(一)

时间:2023-03-09 13:23:57
Threading Module源码概述(一)

  Python的Threading模块是建立在thread module基础上的一个模块,在threading模块中,暴露着许多thread模块的属性。比如threading._get_ident实际上就是thread.get_ident.

 _start_new_thread = thread.start_new_thread
_allocate_lock = thread.allocate_lock
_get_ident = thread.get_ident
ThreadError = thread.error

  在threading模块中,有一套记录当前所有通过继承threading.Thread而创建的python线程的机制。这个机制通过两个dict 和一个lock完成。

 # Active thread administration
_active_limbo_lock = _allocate_lock()
_active = {} # maps thread id to Thread object
_limbo = {}

threading.py

  我们知道通过threading.Thread创建多线程有两个阶段。

  第一个阶段调用threading.Thread.start

  第二个阶段是在threading.Thread.start中调用threading.Thread.run。

  当处于第一阶段时,还没有调用thread.start_new_thread创建原生子线程,这时候把线程记录在了_limbo中。由于没有创建子线程,所以现在没有线程id,记录方式为 _limbo[self] = self。在第二阶段,已经成功地调用thread.start_new_thread创建原生子线程,这时将从_limbo中删除子线程,而将子线程记录到_active中,记录方式为_active[self.__ident] = self 或者_active[thread_id] = thread。可见,这Python这两个dict分别维护了自己已经创建和等待创建的子线程集合。对这两个dict的访问都在_active_limbo_lock的保护之下进行。

 def start(self):
with _active_limbo_lock:
_limbo[self] = self #将线程添加到dict中

第一步

 def start(self):
try: #调用_start_new_thread创建子线程
_start_new_thread(self.__bootstrap, ()) def __bootstrap(self):
try:
self.__bootstrap_inner() def __bootstrap_inner(self):
try:
self._set_ident() #获得线程id
self.__started.set()
with _active_limbo_lock:
_active[self.__ident] = self #将线程id保存到_active的dict
del _limbo[self] #移除之前limbo字典中的线程

第二步