class multiprocessing.
JoinableQueue
([maxsize])
, a subclass, is a queue which additionally has and methods.
-
Indicate that a formerly enqueued task is complete. Used by queue consumers. For each used to fetch a task, a subsequent call to tells the queue that the processing on the task is complete.
If a is currently blocking, it will resume when all items have been processed (meaning that a call was received for every item that had been into the queue).
Raises a if called more times than there were items placed in the queue.
task_done
() -
Block until all items in the queue have been gotten and processed.
The count of unfinished tasks goes up whenever an item is added to the queue. The count goes down whenever a consumer calls to indicate that the item was retrieved and all work on it is complete. When the count of unfinished tasks drops to zero, unblocks.
这是官网对JoinableQueue的概述,我们通过这个方法就可以实现我们自己的生产者消费者模型,具体的实现思路请看我的分析<<>>
code如下:
import multiprocessingdef printAll(queue, out_queue): while 1: t = queue.get() print(t) s = "生产{0}".format(t) queue.task_done() out_queue.put(s)if __name__ == "__main__": queue = multiprocessing.JoinableQueue() num_consumer = multiprocessing.cpu_count() * 2 out_queue = multiprocessing.Queue() for i in range(250): queue.put(i) for _ in range(num_consumer): p = multiprocessing.Process(target=printAll, args=(queue, out_queue)) p.start() queue.join() # 阻塞队列直到队列为空。 result = [] print("数量是: {}".format(out_queue.qsize())) while out_queue.qsize() != 0: result.append(out_queue.get()) for i in result: print(i)
简单地实现了我要的结果,具体可以再项目中应用上。
join
()