我在 python 中遇到这个问题:
- 我有一个 URL 队列,需要时不时地检查一下
- 如果队列已满,我需要处理队列中的每个项目
- 队列中的每个项目必须由单个进程处理(多处理)
到目前为止,我设法“手动”实现这一点,如下所示:
while 1:
self.updateQueue()
while not self.mainUrlQueue.empty():
domain = self.mainUrlQueue.get()
# if we didn't launched any process yet, we need to do so
if len(self.jobs) < maxprocess:
self.startJob(domain)
#time.sleep(1)
else:
# If we already have process started we need to clear the old process in our pool and start new ones
jobdone = 0
# We circle through each of the process, until we find one free ; only then leave the loop
while jobdone == 0:
for p in self.jobs :
#print "entering loop"
# if the process finished
if not p.is_alive() and jobdone == 0:
#print str(p.pid) + " job dead, starting new one"
self.jobs.remove(p)
self.startJob(domain)
jobdone = 1
然而,这会导致大量的问题和错误。我想知道我是否更适合使用进程池。这样做的正确方法是什么?
然而,很多时候我的队列是空的,并且一秒钟可以被 300 个项目填满,所以我不太确定如何在这里做事。
您可以使用以下的阻止功能queue在启动时生成多个进程(使用multiprocessing.Pool)并让它们休眠,直到队列中有一些数据可供处理。如果您对此不熟悉,您可以尝试“玩”这个简单的程序:
import multiprocessing
import os
import time
the_queue = multiprocessing.Queue()
def worker_main(queue):
print os.getpid(),"working"
while True:
item = queue.get(True)
print os.getpid(), "got", item
time.sleep(1) # simulate a "long" operation
the_pool = multiprocessing.Pool(3, worker_main,(the_queue,))
# don't forget the comma here ^
for i in range(5):
the_queue.put("hello")
the_queue.put("world")
time.sleep(10)
Tested with Python 2.7.3 on Linux
这将产生 3 个进程(除了父进程之外)。每个孩子执行worker_main
功能。这是一个简单的循环,在每次迭代时从队列中获取一个新项目。如果没有任何东西可以处理,工人将阻塞。
启动时,所有 3 个进程都会休眠,直到队列收到一些数据。当数据可用时,等待的工作人员之一会获取该数据并开始处理它。之后,它尝试从队列中获取其他项目,如果没有可用的,则再次等待......
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)