python threading ThreadPoolExecutor源码解析
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源码解析的更多相关文章
- python Threading模块源码解析
查看源码: 这是一个线程控制的类,这个类可以被子类化(继承)在一定的条件限制下,这里有两种方式去明确活动:第一通过传入一个callable 对象也就是调用对象,一种是通过重写这个Thread类的run ...
- python threading Future源码解析
1. Future内部还是用了condition这个锁 2. Cancel # future在执行时,会一直更新这个状态 def cancel(self): """Can ...
- ThreadPoolExecutor系列<三、ThreadPoolExecutor 源码解析>
本文系作者原创,转载请注明出处:http://www.cnblogs.com/further-further-further/p/7681826.html 在源码解析前,需要先理清线程池控制的运行状态 ...
- ThreadPoolExecutor系列三——ThreadPoolExecutor 源码解析
ThreadPoolExecutor 源码解析 本文系作者原创,转载请注明出处:http://www.cnblogs.com/further-further-further/p/7681826.htm ...
- 第十三章 ThreadPoolExecutor源码解析
ThreadPoolExecutor使用方式.工作机理以及参数的详细介绍,请参照<第十二章 ThreadPoolExecutor使用与工作机理 > 1.源代码主要掌握两个部分 线程池的创建 ...
- Java并发包源码学习系列:线程池ThreadPoolExecutor源码解析
目录 ThreadPoolExecutor概述 线程池解决的优点 线程池处理流程 创建线程池 重要常量及字段 线程池的五种状态及转换 ThreadPoolExecutor构造参数及参数意义 Work类 ...
- Java并发之ThreadPoolExecutor源码解析(二)
ThreadPoolExecutor ThreadPoolExecutor是ExecutorService的一种实现,可以用若干已经池化的线程执行被提交的任务.使用线程池可以帮助我们限定和整合程序资源 ...
- 【Java并发编程】21、线程池ThreadPoolExecutor源码解析
一.前言 JUC这部分还有线程池这一块没有分析,需要抓紧时间分析,下面开始ThreadPoolExecutor,其是线程池的基础,分析完了这个类会简化之后的分析,线程池可以解决两个不同问题:由于减少了 ...
- Java 1.7 ThreadPoolExecutor源码解析
Java中使用线程池技术一般都是使用Executors这个工厂类,它提供了非常简单方法来创建各种类型的线程池: public static ExecutorService newFixedThread ...
随机推荐
- 【计算机网络】UDP基础知识总结
1. UDP概念相关 [!NOTE] UDP(User Datagram Protocol),又叫用户数据报协议. UDP是一个无连接的.不可靠.基于数据报的传输协议.UDP只是报文(报文可以理解为一 ...
- attention 汇总(持续)
Seq2seq Attention Normal Attention 1. 在decoder端,encoder state要进行一个线性变换,得到r1,可以用全连接,可以用conv,取决于自己,这里 ...
- Flink中Idle停滞流机制(源码分析)
前几天在社区群上,有人问了一个问题 既然上游最小水印会决定窗口触发,那如果我上游其中一条流突然没有了数据,我的窗口还会继续触发吗? 看到这个问题,我蒙了???? 对哈,因为我是选择上游所有流中水印最小 ...
- JAVA语言的环境搭建
1.下载JDK 下载地址 https://www.oracle.com/technetwork/java/javase/downloads/index.html 2.安装JDK 傻瓜式的安装,一直点击 ...
- JS基础语法---for循环遍历数组
for循环遍历数组 要显示数组中的每个数据,可以如下: var arr=[10,20,30,40,50]; //显示数组中的每个数据 console.log(arr[0]); console.log( ...
- 腾讯云游戏服务平台CMatrix品牌全新升级为GameMatrix
近日,隶属腾讯互娱公共研发运营体系(下文称CROS)下的云游戏服务平台CMatrix宣布进行品牌升级,启用全新商标Tencent GameMatrix,将原先代表云服务的“C”替换成游戏的英文单词“G ...
- opencv::DNN介绍
DNN模块介绍: Tiny-dnn模块 支持深度学习框架 - Caffe - TensorFlow - Torch/PyTorch DNN运用 图像分类 对象检测 实时对象检测 图像分割 预测 视频对 ...
- ProtoBuf格式详解
- 数据结构 通过前面的例子,可以看到PB的数据结构就是每项数据独立编码,包含一个表示数据类型 - Varint Varint是一种对数字进行编码的方法,将数字编码成不定长的二进制数据,数值越小,编码 ...
- MBProgressHUD源码(上)
本篇博文记录MBProgressHUD源码学习过程,从官方提供的Demo项目入手,一步步了解其代码结构,学习它使用的技术,体会作者的编程思想. 一.结构 我们先来看下MBProgressHUD的结构, ...
- 用python的time库写一个进度条
运算符 算数运算 如a=10,b=20 +两个数相加 a+b=30 -两个数相减 a-b=-10 两个数相乘 a****b =200 /两个数相除b/a=2 %取模,并返回余数b%a=0 幂,a*** ...