Python多处理队列可靠性,队列vs SimpleQueue vs JoinableQueu

2024-04-29 19:24:11 发布

您现在位置:Python中文网/ 问答频道 /正文

直接从Pythondocs

class multiprocessing.Queue([maxsize])

...

qsize() Return the approximate size of the queue. Because of multithreading/multiprocessing semantics, this number is not reliable.

empty() Return True if the queue is empty, False otherwise. Because of multithreading/multiprocessing semantics, this is not reliable.

根据经验我发现这对Queue来说是非常正确的,尤其是对empty()

在我的代码中,我有一堆进程(每个进程都是同一主进程的子进程),每个进程的run方法中都有以下内容:

while self.active:
    if(self.exclusive_queue.empty() and self.exclusive_queue.qsize() == 0):
        try:
            self.exclusive_queue.put(self.general_queue.get(timeout=self.queue_timeout))
        except Queue.Empty as empty_queue:
            continue
    else:
        task = self.exclusive_queue.get()
        self.compute(task)

基本上,进程等待general_queue工作,但首先检查它的exclusive_queue。主进程可以将任务放入进程的常规队列或独占队列中。现在,在if(self.exclusive_queue.empty() and self.exclusive_queue.qsize() == 0)中,我首先使用了self.exclusive_queue.empty(),这导致了相当奇怪的行为(qsize()的30+和empty() = True)。

因此,我在文档中的标题是-for multiprocessing.queues.SimpleQueue

empty() Return True if the queue is empty, False otherwise.

完全没有提到可靠性。SimpleQueue.empty()可靠吗?

第二,由于task_done()机制,multiprocessing.JoinableQueue可靠还是比Queue更可靠?

这样的方法是否可以被认为是正确的,或者(通过子级之间的共享管道端点)回调的方法更合适?


Tags: ofthe方法selftruereturnifqueue
1条回答
网友
1楼 · 发布于 2024-04-29 19:24:11

不是直接的答案,但我已经开始越来越依赖于使用保护条件迭代输入队列。在多处理模块的文档中有一个示例:

def worker(input, output):
    for func, args in iter(input.get, 'STOP'):
        result = calculate(func, args)
        output.put(result)

因此,当您对队列的输入完成时,您只需在启动进程时对队列使用put尽可能多的STOP字符串,或选择任何保护措施。

相关问题 更多 >