Python 为什么要进行多重处理。进程不';空队列后是否初始化?
我被一个问题困住了,找不到好答案 我有一个脚本,它从一个文件夹中获取图像,然后放入一个我命名为pool的队列。在while true循环中,我验证文件夹中是否有图像。是的,我拍摄了这些图像并将其放入这个池队列,因此我创建了一些进程,这些进程将运行一个函数来验证这些图像上是否有人脸,并执行其他无关的操作 我的问题从代码中变得异常平静。如果文件夹中有图像,他们会为每个进程分发一个图像,这没关系。但如果图像少于进程,或者文件夹为空,则在我将新图像放入文件夹时不会创建进程 有什么解释吗 以下是代码的相关部分:Python 为什么要进行多重处理。进程不';空队列后是否初始化?,python,python-2.7,python-multiprocessing,Python,Python 2.7,Python Multiprocessing,我被一个问题困住了,找不到好答案 我有一个脚本,它从一个文件夹中获取图像,然后放入一个我命名为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()
问题:。。。当我在文件夹中放置新图像时,进程尚未创建
您可以在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使用
循环
条件在面部搜索
中编辑您的问题。表示您的进程是等待新映像可用还是在处理映像后退出?它在处理映像后退出。而while true循环对下一个图像进行相同的处理。