Python 多线程:如何在已存在的工作对象之间共享参数队列?

问题描述 投票:0回答:1

我有 5 个工作人员(“处理器”),应该使用特定方法 (

process()
) 处理 100 个参数(可能在某种队列中?)。我希望 5 个“处理器”并行执行。我研究了
concurrent.futures
multiprocessing
,但找不到这样的例子

import time
import numpy as np

class Processor :

    def __init__(self, name) :
        self.name = name

    def process(self, arg) :
        print(f'{self.name} : processing {arg}...')
        time.sleep(arg)
        print(f'{self.name} : processing {arg}... DONE')

l_processors = [Processor(f'Processor_{i}') for i in range(5)]
l_arguments = list(range(10))
np.random.shuffle(l_arguments)

# ... what to write beyond this point ?

有什么想法吗? 预先感谢您的任何答复。

PS:

  • 要使用这5个Processor对象,我不能使用已经做好的全包装的“ProcessorPool(n_workers=5)”
  • 我不想将每个工作人员“处理器”预先分配给参数列表。我无法提前知道每个争论需要多长时间(就时间而言)。相反,当工人有空时,他应该查看参数队列并选择下一个。
python multithreading multiprocessing
1个回答
0
投票

我找到了一种方法(也许不是最好的方法,我愿意接受反馈):

from multiprocessing import Process, Queue

# populate a Queue of arguments :
q = Queue()
for arg in l_arguments :
    q.put(arg)
    
# creating a pool of Processes : (Manually) :
def process_next_one(worker, q) :
    arg = q.get()
    worker.do_something(arg)
    
l_processes = [
    Process(target=process_next_one, args=(worker, q))
    for worker in l_workers]

# Making the Processes run in parallel :
for p in l_processes :
    p.start()
for p in l_processes :
    p.join()
© www.soinside.com 2019 - 2024. All rights reserved.