繁体   English   中英

为什么multiprocessing.Process在空队列之后没有初始化?

[英]Why multiprocessing.Process don't initialize after empty queue?

我遇到一个问题,找不到一个好的答案。

我有一个脚本,该脚本从文件夹中获取图像,然后放入我命名为pool的Queue中。 在一段时间的真实循环中,我验证文件夹中是否有图像。 是的,我将这些图像放入此队列并放入池中,因此我创建了流程,该流程将运行一个函数来验证这些图像上是否有面孔,并进行其他不相关的事情。

我的问题来自代码的异常补充。 如果文件夹中有图像,则它们可以为每个处理蚂蚁分配一张图像。 但是,如果图像少于进程,或者文件夹为空,则当我将新图像放入文件夹时,不会创建进程。

有什么解释吗?

这是代码的相关部分:

def face_search(pool, qtd_pool):
  # Do face recognition and move files
  # When files moved, the folder with images get empty until i put new images
  # if there's no face, the image is deleted from disk
  # At the end, it return True and enter in the next image loop

if __name__ == '__main__':
  #irrelevant stuff
  while true:
    pool_get = os.listdir(/some_directory/)
    qtd_pool = len(pool_get)
    pool = Queue()

    for image in pool_get:
      pool.put('/some_directory/'+image)

    # down below i create the Process, and join then when finished. They would be created for every loop, right? Why they don't act like that?
    procs = [Process(target = face_search, args=(pool, qtd_pool, )) for i in xrange(nthreads)]

    for p in procs: p.start()
    for p in procs: p.join()

问题 :...当我将新图像放入文件夹时,未创建进程。

您可以在while循环内完成所有操作 ,如果文件夹为空,则没有任何条件。 我假设您没有使用新创建的进程使系统过载。

考虑这种方法, 一次创建您的流程然后让它们等待,直到准备好新映像为止。

def face_search(exit_process, job_queue):
    while not exit_process.is_set():
        try:
            job = job_queue.get_nowait()
            # Do image processing

        except queue.Empty:
            time.sleep(0.5)

    exit(0)

def process_images(job_queue):
    path = '.'
    for fname in os.listdir(path):
        job_queue.put(os.path.join(path, fname))


if __name__ == '__main__':
    exit_process = mp.Event()
    job_queue = mp.Manager().Queue()

    pool = []
    for n in range(mp.cpu_count()):
        p = mp.Process(target=face_search, args=(exit_process, job_queue))
        p.start()
        pool.append(p)
        time.sleep(0.1)

    process_images(job_queue)

    # Block until all jobs done
    while not job_queue.empty():
        time.sleep(1)

    # Stop Processes
    exit_process.set()

使用Python测试:3.4.2和2.7.9

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM