zoukankan      html  css  js  c++  java
  • 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字典中的线程
    第二步
  • 相关阅读:
    sql 读取txt 文件内容,并写入sql的方法
    Thread.Mutex 互斥体
    SQL语句创建登录名,数据库用户,数据库角色及分配权限:
    倾国倾城 歌词
    LINUX下c/c++的学习(4)linux file and direction(stat fstat lstat access umask chmod ...)
    飞蛾扑火
    生成验证码点击可刷新
    C#项目调用非托管代码函数的方法
    【学习】数据库事务
    如何判断数据库是否存在
  • 原文地址:https://www.cnblogs.com/chenchao1990/p/5103734.html
Copyright © 2011-2022 走看看