日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 人文社科 > 生活经验 >内容正文

生活经验

python threading ThreadPoolExecutor源码解析

發布時間:2023/11/27 生活经验 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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) #實現的是queueself._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 queuet.daemon = Truet.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 issue16284del work_itemcontinueexecutor = 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)returndel executorexcept BaseException:_base.LOGGER.critical('Exception in worker', exc_info=True)

?

?

4. WorkItem

class _WorkItem(object):def __init__(self, future, fn, args, kwargs):self.future = futureself.fn = fnself.args = argsself.kwargs = kwargsdef run(self):if not self.future.set_running_or_notify_cancel():returntry: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 = Noneelse:self.future.set_result(result)

?

轉載于:https://www.cnblogs.com/callyblog/p/11147946.html

總結

以上是生活随笔為你收集整理的python threading ThreadPoolExecutor源码解析的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。