带有不同工人计数的嵌套线池

发布于 2025-01-22 15:34:56 字数 896 浏览 4 评论 0原文

我已经开始学习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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文