Threading Module源码概述(一)

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

1 _start_new_thread = thread.start_new_thread
2 _allocate_lock = thread.allocate_lock
3 _get_ident = thread.get_ident
4 ThreadError = thread.error
View Code

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

1 # Active thread administration
2 _active_limbo_lock = _allocate_lock()
3 _active = {}    # maps thread id to Thread object
4 _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的保护之下进行。

1 def start(self):
2         with _active_limbo_lock:
3             _limbo[self] = self  #将线程添加到dict中
第一步
 1 def start(self):
 2         try:        #调用_start_new_thread创建子线程
 3             _start_new_thread(self.__bootstrap, ())
 4 
 5 def __bootstrap(self):
 6     try:
 7         self.__bootstrap_inner() 
 8 
 9 def __bootstrap_inner(self):
10     try:
11         self._set_ident()   #获得线程id
12         self.__started.set()
13         with _active_limbo_lock:
14             _active[self.__ident] = self   #将线程id保存到_active的dict
15             del _limbo[self]   #移除之前limbo字典中的线程
第二步

posted on 2016-01-05 21:36  让我们忘了那片海  阅读(977)  评论(0编辑  收藏  举报

导航