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. 数据库——数据库设计 E-R图向关系模型的转换

    1.将下列物资管理E-R图转换为关系模式: 转换原则 ⒈  一个实体型转换为一个关系模式.关系的属性:实体型的属性关系的码:实体型的码   ⒉ 一个m:n联系转换为一个关系模式(初步,以后可能调整). ...

  2. 利用代码生成工具生成基于ABP框架的代码

    在前面随笔,我介绍了整个ABP优化过框架的分层模型,包括尽量简化整个ABP框架的各个层的关系,以及纳入一些基类的辅助处理,使得我们对应业务分层类或者接口尽可能减少代码,并具有生产环境所需要的基类接口, ...

  3. 2018-8-10-win10-uwp-重启软件

    原文:2018-8-10-win10-uwp-重启软件 title author date CreateTime categories win10 uwp 重启软件 lindexi 2018-08-1 ...

  4. 练手WPF(一)——模拟时钟与数字时钟的制作(中)

    今天接着制作数字时钟 数字时钟主要用到Path控件,主要用于定义数字笔划的形状. (1)添加一个DigitLine类 数字时钟的数字8由7笔组成,看如下定义的字段字符串数组PathDatas,每个st ...

  5. WPF ListBox 隐藏滑块

    <ListBox ScrollViewer.VerticalScrollBarVisibility = "Disabled"; </ListBox>

  6. .net ajax跨域请求问题

    </system.codedom>     <system.webServer>         <defaultDocument>             < ...

  7. Docker是什么、为什么是一种趋势

    Docker的思想来自于集装箱,集装箱解决了什么问题?在一艘大船上,可以把货物规整的摆放起来.并且各种各样的货物被集装箱标准化了,集装箱和集装箱之间不会互相影响.那么我就不需要专门运送水果的船和专门运 ...

  8. JavaWeb之Cookie&Session

    Cookie 直译是:小饼干.实际上,Cookie就是由服务器给客户端,并且存储在客户端上的一份小数据 应用场景 自动登录,查看浏览记录,购物车 Cookie存在的意义 HTTP请求是无状态的,客户端 ...

  9. PHP odbc_errormsg ODBC 函数

    定义和用法 odbc_errormsg - 获取最后一条错误消息 语法 odbc_errormsg ( [ resource $connection_id ] ) 返回包含最后一个ODBC错误消息的字 ...

  10. git安装和项目上传到GitHub

    重装系统后,Git安装也要来重来 下载 国内下载地址:https://npm.taobao.org/mirrors/git-for-windows 安装忽略 生成密钥 输入然后都是下一步,生成密钥,生 ...