队列多处理问题

蒂莫西·黄

情况:我有一个用 Python 编写的文件处理器。这些文件将被“遍历”并放入队列中。然后将使用multirocessing

问题:参考下面的代码

fileA.py
==========
import Queue
import os
def walker():
    filelist = Queue.Queue()
    queue_end = Object()
    for root, dirs, files in os.walk('/'):
        for f in files:
            path = os.path.join(root,f)
            if not os.path.islink(path):
                filelist.put(path)
    filelist.put(queue_end)

fileB.py
===========
import fileA
import os
import multiprocessing as mp

def processor(queuelock):
    while True:
        with queuelock:
            filepath = fileA.filelist.get()

            if filepath is fileA.queue_end:
                filelist.put(queue_end)
                break
        #example of a job
        os.move(filepath, "/home/newuser" + filepath)
        print filepath + " has been moved!"

if __name__ == '__main__':
    fileA.walker()
    queuelock = mp.Lock()
    jobs = []
    for i in range(0,mp.cpu_count()):
        process = mp.Process(target=processor(queuelock))
        jobs.append(process)
        process.start()

问题是当文件被移动时,所有进程都将尝试移动完全相同的文件,即使它应该已从队列中删除。

示例输出:

randomFile as been moved!
Error: ......... randomFile not found
Error: ......... randomFile not found
Error: ......... randomFile not found

从而暗示产生的每个进程都使完全相同的文件出列并试图对同一个文件执行相同的进程。

问题:我做错了什么,出于某种原因,filelist队列已发送到每个进程(现在发生了什么),而不是filelist所有进程共享队列(我的预期结果)?

迈克尔·布彻
  1. filelist目前只是一个局部变量,walker()并且队列对象不与代码的其他部分共享,因此return filelistwalker().

  2. 要在多个进程之间共享同一个队列,multiprocessing.Queue需要一个。queue.Queue当进程被派生(或派生)时,A被复制,因此它成为每个进程的新独立队列。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章