带有不同工人计数的嵌套线池
我已经开始学习Python,并遇到了一个场景,我必须实现两个单独的队列:
- 我有n个流程和两个操作,O1和O2。
- 我想和4名工人一起运行O1。
- O2和1个工人
我当前的代码:
import time
from concurrent.futures import ThreadPoolExecutor
PROCESS_NUM = 4
o1_exe = ThreadPoolExecutor(max_workers=4)
o2_exe = ThreadPoolExecutor(max_workers=1)
def O1(x: int):
print(f'O1: {x} started')
time.sleep(1)
print(f'O1: {x} complete')
def O2(x: int):
print(f'O2: {x} started')
time.sleep(2)
print(f'O2: {x} complete')
def process(x: int):
O1(x)
o2_exe.submit(O2, x)
for i in range(0, PROCESS_NUM):
o1_exe.submit(process, i)
我将获得以下输出:
O1: 0 started
O1: 0 complete
O1: 1 started
O1: 1 complete
O1: 2 started
O1: 2 complete
O1: 3 started
O1: 3 complete
代码的问题是O2根本不运行。
还有其他方法可以使这项工作或使用不同的方法解决方案吗?
我目前正在使用Python 3.9.7
I've started learning Python and came across a scenario where I have to implement two separate queues:
- I have N processes and two operations, O1 and O2.
- I want to run O1 with 4 workers.
- And O2 with 1 worker
My current code:
import time
from concurrent.futures import ThreadPoolExecutor
PROCESS_NUM = 4
o1_exe = ThreadPoolExecutor(max_workers=4)
o2_exe = ThreadPoolExecutor(max_workers=1)
def O1(x: int):
print(f'O1: {x} started')
time.sleep(1)
print(f'O1: {x} complete')
def O2(x: int):
print(f'O2: {x} started')
time.sleep(2)
print(f'O2: {x} complete')
def process(x: int):
O1(x)
o2_exe.submit(O2, x)
for i in range(0, PROCESS_NUM):
o1_exe.submit(process, i)
I get the following Output:
O1: 0 started
O1: 0 complete
O1: 1 started
O1: 1 complete
O1: 2 started
O1: 2 complete
O1: 3 started
O1: 3 complete
The issue with my code is that O2 isn’t running at all.
Is there any other way to make this work or some solution with different approach?
I’m currently using Python 3.9.7
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论