我遇到了一个问题,我找不到一个好的答案。
我有一个脚本从文件夹中获取图像然后放入我命名为pool的队列中。在 while true 循环中,我验证文件夹中是否有图像。是的,我把这些图像放到这个池队列中,所以我创建了一个进程来运行一个函数来验证这些图像上是否有面孔,并做其他不相关的事情。
我的问题来自代码的不寻常的契合。如果在文件夹中有图像,它们会为每个进程蚂蚁分配一个图像,这是可以的。但如果图像的数量少于进程,或者文件夹为空,则在将新图像放入文件夹时,不会创建进程。
有没有解释?
以下是代码的相关部分:
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()
答案 0 :(得分:0)
问题:...当我将新图像放入文件夹时,尚未创建进程。
你在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