python - Python 的 ThreadPoolExecutor 是否重用相同的线程池,或者任何线程都可以在某个时间点被杀死和替换?
问题描述
基本上,标题。
这个问题可以用这个片段来证明:
from time import sleep
from concurrent.futures import ThreadPoolExecutor, wait
from threading import get_ident, Lock
WORKERS = 5
thread_ids = []
thread_ids_lock = Lock()
def main():
executor = ThreadPoolExecutor(max_workers=WORKERS)
futures = []
for _ in range(10_000):
futures.append(executor.submit(do_work))
wait(futures)
def do_work():
thread_id = get_ident()
if thread_id not in thread_ids:
with thread_ids_lock:
thread_ids.append(thread_id)
# Is this guaranteed to always be true?
assert len(thread_ids) <= WORKERS, 'Too many thread IDs'
thread_num = thread_ids.index(thread_id) + 1
print(f'[Thread #{thread_num}] Doing work...')
sleep(0.01)
print(f'[Thread #{thread_num}] Done')
if __name__ == '__main__':
main()
ps 它说“看起来你的帖子主要是代码;请添加更多细节”,但我觉得我没有什么要添加的,所以我只是输入这个:)
解决方案
推荐阅读
- typescript - Vue.js 打字稿损坏
- microsoft-graph-api - MS Graph lastModifiedDateTime 和 SharePoint REST API TimeLastModified 对于同一个文件是不同的
- ios - 为什么 swift 函数被编译 25 次?
- java - Android中的自定义最大异步任务
- excel - 从excel列中选择最大值并检查条件是否匹配
- php - 在我的 android 应用程序中获取 json 格式的数据时出错
- ruby-on-rails - collection_select 中的选项在提交时创建一个新选项 - Rails 5
- asp.net-core - Razor 页面中基于 URL 参数的路由
- sql - 有没有办法在 Redshift 上返回用户定义的函数内容(查询)?
- ios - 页面控制在完全进入下一页之前切换页面