302766392
V2EX  ›  Python

关于 ThreadPoolExecutor 的问题

By 302766392 at 2018 年 7 月 27 日 · 3345 次点击
Code:
--------------------------------------------------------------
import time
from concurrent.futures import ThreadPoolExecutor

def work_01(i):
time.sleep(1)
print(i)

def work_02(i):
time.sleep(2)
print(i)

def work_03(i):
time.sleep(3)
print(i)

with ThreadPoolExecutor(max_workers=5) as executor:
for i in range(2):
executor.submit(work_01, i)
executor.submit(work_02, i)
executor.submit(work_03, i)

print('over')
-------------------------------------------------------------------

return:
-------------------------------------------------------------------
0
1
0
1
0
1
over
-------------------------------------------------------------------

question:
-------------------------------------------------------------------
1. 在这里提问题怎么上传图片呀?
2. executor.submit(work_01, i) executor.submit(work_02, i) executor.submit(work_03, i)
这三个任务是需要依次顺序执行的,仅在三个任务顺序执行完再一次性打印结果,这有
点类似于 mysql 的组合唯一值,同时我的线程池也是生效的,不会等待 3 个任务执行完再
执行下 3 个任务
3. 理想的展示效果如下:
0
0
0
1
1
1
over

或

1
1
1
0
0
0
over
-------------------------------------------------------------------
6 条回复  •  2018-07-28 08:53:07 +08:00
shangfabao
   1
shangfabao  
   2018 年 7 月 27 日
数量设置为 1,先后添加,然后监听所有线程执行完,java 是这么做的
owenliang
   2
owenliang  
   2018 年 7 月 27 日
了解一下互斥锁+条件变量,构造一个 future,每个线程执行完成后++完成次数,在主线程里 condition wait 等待 3 个都完成,则返回。
whoami9894
   3
whoami9894  
   2018 年 7 月 27 日 via Android
六个任务相当于同时开始,sleep(1)的两个最先执行完打印结果
yuan93
   4
yuan93  
   2018 年 7 月 27 日
给业务上要等待其他线程的所有线程维护一个 countdownlatch ?
8rB61FLBPVSxW2C8
   5
8rB61FLBPVSxW2C8  
   2018 年 7 月 27 日
线程同步,了解下
lolizeppelin
   6
lolizeppelin  
   2018 年 7 月 28 日 via Android
结果塞到队列里 不用加锁
推荐学习书目
› Learn Python the Hard Way
Python Sites
› PyPI - Python Package Index
› http://diveintopython.org/toc/index.html
› Pocoo
值得关注的项目
› PyPy
› Celery
› Jinja2
› Read the Docs
› gevent
› pyenv
› virtualenv
› Stackless Python
› Beautiful Soup
› 结巴中文分词
› Green Unicorn
› Sentry
› Shovel
› Pyflakes
› pytest
Python 编程
› pep8 Checker
Styles
› PEP 8
› Google Python Style Guide
› Code Style from The Hitchhiker's Guide
© 2026 V2EX · 38ms · 3.9.8.5