为什么多进程.Process在空队列后不初始化?

2024-04-26 02:26:19 发布

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

我被一个问题搞糊涂了,找不到一个好的答案。在

我从一个名为“谁”的文件夹中取出一个名为“谁”的图像。在while true循环中,我验证文件夹中是否有图像。对于yes,我将这些图像放入这个池队列中,因此我创建了一些进程,这些进程将运行一个函数来验证这些图像上是否有人脸,并执行其他无关的操作。在

我的问题从代码中得到了不同寻常的回答。如果文件夹中有图像,它们会为每个进程分配一个映像,这是可以的。但是如果图像少于进程,或者文件夹是空的,那么当我把新的图像放入文件夹时,这些进程就不会被创建。在

有什么解释吗?在

以下是代码的相关部分:

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()

Tags: andthein图像image文件夹truefor
1条回答
网友
1楼 · 发布于 2024-04-26 02:26:19

Question: ... the processes are not been created when i put new images in folder.

while循环中执行all操作,如果文件夹为空,则不需要任何条件。 我假设你用新创建的进程使你的系统过载,什么也不做。在

考虑这种方法,创建一次进程,让它们等待一个新映像就绪。在

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进行测试

相关问题 更多 >