future: 未来对象,或task的返回容器

1. 当submit后:

    def submit(self, fn, *args, **kwargs):
with self._shutdown_lock: # lock是线程锁
if self._shutdown:
raise RuntimeError('cannot schedule new futures after shutdown') f = _base.Future() # 创建future对象
w = _WorkItem(f, fn, args, kwargs) # 线程池执行基本单位 self._work_queue.put(w) #实现的是queue
self._adjust_thread_count() # 这里会进行判断当前执行线程的数量
return f

2. _adjust_thread_count:

    def _adjust_thread_count(self):
# When the executor gets lost, the weakref callback will wake up
# the worker threads.
def weakref_cb(_, q=self._work_queue):
q.put(None)
# TODO(bquinlan): Should avoid creating new threads if there are more
# idle threads than items in the work queue.
num_threads = len(self._threads)
if num_threads < self._max_workers:
thread_name = '%s_%d' % (self._thread_name_prefix or self,
num_threads)
t = threading.Thread(name=thread_name, target=_worker,
args=(weakref.ref(self, weakref_cb),
self._work_queue)) # 创建线程,并调用_worker方法,传入work queue
t.daemon = True
t.start()
self._threads.add(t)
_threads_queues[t] = self._work_queue

3. _worker:

def _worker(executor_reference, work_queue):
try:
while True:
work_item = work_queue.get(block=True)
if work_item is not None:
work_item.run()
# Delete references to object. See issue16284
del work_item
continue
executor = executor_reference()
# Exit if:
# - The interpreter is shutting down OR
# - The executor that owns the worker has been collected OR
# - The executor that owns the worker has been shutdown.
if _shutdown or executor is None or executor._shutdown:
# Notice other workers
work_queue.put(None)
return
del executor
except BaseException:
_base.LOGGER.critical('Exception in worker', exc_info=True)

4. WorkItem

class _WorkItem(object):
def __init__(self, future, fn, args, kwargs):
self.future = future
self.fn = fn
self.args = args
self.kwargs = kwargs def run(self):
if not self.future.set_running_or_notify_cancel():
return try:
result = self.fn(*self.args, **self.kwargs)
except BaseException as exc:
self.future.set_exception(exc)
# Break a reference cycle with the exception 'exc'
self = None
else:
self.future.set_result(result)

python threading ThreadPoolExecutor源码解析的更多相关文章

  1. python Threading模块源码解析

    查看源码: 这是一个线程控制的类,这个类可以被子类化(继承)在一定的条件限制下,这里有两种方式去明确活动:第一通过传入一个callable 对象也就是调用对象,一种是通过重写这个Thread类的run ...

  2. python threading Future源码解析

    1. Future内部还是用了condition这个锁 2. Cancel # future在执行时,会一直更新这个状态 def cancel(self): """Can ...

  3. ThreadPoolExecutor系列<三、ThreadPoolExecutor 源码解析>

    本文系作者原创,转载请注明出处:http://www.cnblogs.com/further-further-further/p/7681826.html 在源码解析前,需要先理清线程池控制的运行状态 ...

  4. ThreadPoolExecutor系列三——ThreadPoolExecutor 源码解析

    ThreadPoolExecutor 源码解析 本文系作者原创,转载请注明出处:http://www.cnblogs.com/further-further-further/p/7681826.htm ...

  5. 第十三章 ThreadPoolExecutor源码解析

    ThreadPoolExecutor使用方式.工作机理以及参数的详细介绍,请参照<第十二章 ThreadPoolExecutor使用与工作机理 > 1.源代码主要掌握两个部分 线程池的创建 ...

  6. Java并发包源码学习系列:线程池ThreadPoolExecutor源码解析

    目录 ThreadPoolExecutor概述 线程池解决的优点 线程池处理流程 创建线程池 重要常量及字段 线程池的五种状态及转换 ThreadPoolExecutor构造参数及参数意义 Work类 ...

  7. Java并发之ThreadPoolExecutor源码解析(二)

    ThreadPoolExecutor ThreadPoolExecutor是ExecutorService的一种实现,可以用若干已经池化的线程执行被提交的任务.使用线程池可以帮助我们限定和整合程序资源 ...

  8. 【Java并发编程】21、线程池ThreadPoolExecutor源码解析

    一.前言 JUC这部分还有线程池这一块没有分析,需要抓紧时间分析,下面开始ThreadPoolExecutor,其是线程池的基础,分析完了这个类会简化之后的分析,线程池可以解决两个不同问题:由于减少了 ...

  9. Java 1.7 ThreadPoolExecutor源码解析

    Java中使用线程池技术一般都是使用Executors这个工厂类,它提供了非常简单方法来创建各种类型的线程池: public static ExecutorService newFixedThread ...

随机推荐

  1. Fragment生命周期函数调用(ViewPager切换方式)

    在使用ViewPager时,Google亲爹为我们提供了多种PagerAdapter.其中,与Fragment相关的是FragmentPagerAdapter和FragmentStatePagerAd ...

  2. django5-书籍与出版社关联外键

    1.外键相关 一对多的概念 ,这里是一个出版社对应本书籍 ! 设计表使用model models.ForeignKey('关联一', on_delete=models.CASCADE) #给多设置外键 ...

  3. ADB控制手机命令(adb命令)

    手机端配置tcp方式连接 su setprop service.adb.tcp.port 5555 stop adbd start adbd 首先使用管理员权限,然后打开监听5555端口 电脑端使用a ...

  4. 微信小程序使用weui构建搜索栏(searchbar)+导航(navbar)

    首先需要在lib目录中添加weui.wxss.searchbar和navbar结合主要解决两者的层次问题,即搜索框输入时,下方的检索结果能够覆盖住navbar.下面就开始发码啦: (1)wxml部分: ...

  5. iOS开发证书那点事儿

    iOS开发是用Xcode作为开发工具,Xcode在安装之后就自带了模拟器(Simulator).模拟器是个好工具,它对用户没有任何要求,但是我们必须牢记一件事:开发出来的App最终是要在真机上执行,没 ...

  6. 详细设计文档(final)

    1. 引言 1.1编写目的 本部分旨在阐明编写详细设计的目的,面向读者对象. 本文档主要描述各个模块的细节设计,明确软件的结构与实现过程,分析各个模块,描述模块的功能.性能和结构等方面包括模块接口.调 ...

  7. python pip 升级 或者换源

    1. 临时换源python -m pip install --upgrade pip -i https://pypi.douban.com/simple pip国内的一些镜像   阿里云  https ...

  8. Selenium库详解

    Selenium 自动化测试工具,支持多种浏览器 爬虫中解决JS渲染问题

  9. 题解:swj社会摇进阶第二课

    题目链接 思路:按题目推一点点可以得出答案为 sigma (i-k)*n/i+d(n%i>=k) #include<bits/stdc++.h> using namespace st ...

  10. Testng 简介

    Testng是一套开源测试框架,是从Junit继承而来,testng意为test next generation,主要有以下特性: annotations  注释,如 @test @BeforeMet ...