Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 多处理。队列可能会丢失其中的元素_Python_Multiprocessing - Fatal编程技术网

Python 多处理。队列可能会丢失其中的元素

Python 多处理。队列可能会丢失其中的元素,python,multiprocessing,Python,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

我使用
多处理.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

我的队列使用错误吗?

您正在隐藏执行此操作时发生的错误:

   try:
        ad_queue.put(ad)
    except:
        pass

请尝试删除队列中的
,添加块,否则当队列已满或为空时,它将引发异常。请尝试
Manager().queue(),
,或者只使用
SimpleQueue()
而不是
queue(),
,谢谢您的回复,但为什么它与异常部分相关?根据我的理解,由于最终代码将始终被执行,它应该与异常无关~实际上,我在实际代码中使用logger.exception(e),但没有异常loggedthanks,您是指“whilenot ad_queue.empty()”部分?来自多处理。队列使用生产者-消费者模式,它应该已经在其中使用锁了