我使用multiprocessing.Queue
来处理广告制作。但是当使用Queue.get()时,似乎有些元素丢失了(例如,我在队列中放了10个广告,但在多处理工作完成后只处理了8个)。
代码是:
from multiProcessing import Process, Queue, JoinableQueue
def create_ad(origin_queue, ad_queue):
''' ad creation'''
for ad in iter(origin_queue.get, None):
try:
# do sth else
ad_queue.put(ad)
except:
pass
# actually there exists logging here, no error outside
finally:
origin_queue.task_done()
origin_queue.task_done()
if __name__ == '__main__':
origin_queue = JoinableQueue()
# mock to put ads inside
ads = [1,2,3,4,5]
[ origin_queue.put(ad) for ad in ads ]
ad_queue = Queue()
process_list = []
for p in range(4): # PROCESS_NUM
process = Process(target=create_ad, args=(origin_queue, ad_queue))
process_list.append(process)
for process in process_list:
process.daemon = True
process.start()
origin_queue.join()
for process in process_list:
origin_queue.put(None)
origin_queue.join()
while not ad_queue.empty():
ad = ad_queue.get() # number of ad got here is different from ads put inside it
我的队列使用不对吗?
答案 0 :(得分:0)
您隐藏了执行此操作时发生的错误:
try:
ad_queue.put(ad)
except:
pass
尝试删除except
答案 1 :(得分:0)
为你的队列添加块,否则它会引发异常,你已经丢弃,当满或空时。
答案 2 :(得分:0)
尝试使用Manager().Queue()
或仅使用SimpleQueue()
而不是Queue()
。