首页 > Python 中 Queue 的用法?

Python 中 Queue 的用法?

我使用几个生产者得到了一些数据,希望写入 multiprocessing 库创立的 Queue 中,然后由一个消费者读取并做后期处理,请问怎么样写才好,我用 while true 的方式一直假死。
这是主要代码:

q = multiprocessing.Queue(1001)
if __name__ == '__main__':
    q = multiprocessing.Queue(1001)
    pool = multiprocessing.Pool(processes=10)
    for year in [2008]:
        if year is not None:
            pool.apply_async(solve_year, (year,))
    pool.apply_async(consume)
    pool.close()
    pool.join()

在生产者中使用了:

for i in b.list_():
    info_detail = InfoDetail(i)
    for i in info_detail.get_dict():
        d[i] = d[i].encode('utf-8')
    if d.has_key('status'):
        continue
    q.put(d)

这是消费者的部分代码:

while not q.empty():
            d = q.get(block=True)
            print d

下面这行在Queue为空的情况下是会阻塞的,由于没有设置timeout,会一直阻塞到Queue中有数据为止:

q.get(block=True)

另外在多进程中使用empty()判断是不稳定的:
因为当时check时是empty,但check完可能已经被其它进程塞入数据了,
或者当时check时不是empty,但check完可能已经被其它进程取光数据变成empty了。

文档也是这么说的:

empty()
Return True if the queue is empty, False otherwise. Because of
multithreading/multiprocessing semantics, this is not reliable.


Queue中的队列被取空了? 然后Get就阻塞了?
贴个代码看看

【热门文章】
【热门文章】