参考Python官方文档:
The queue module implements multi-producer, multi-consumer queues. It is especially useful in threaded programming when information must be exchanged safely between multiple threads. The Queue class in this module implements all the required locking semantics. It depends on the availability of thread support in Python; see the threading module.
queue模块已经按照多生产者多消费者模型实现了该模块,所以,python的生产者消费者模型代码如下:
from threading import Thread import time import random import queue q = queue.Queue(10) class ProducerThread(Thread): def run(self): nums = range(5) global q while True: num = random.choice(nums) q.put(num) print("Produced", num) time.sleep(random.random()) class ConsumerThread(Thread): def run(self): global q while True: num = q.get() q.task_done() print("Consumed", num) time.sleep(random.random()) ProducerThread().start() ConsumerThread().start()
https://docs.python.org/3.4/library/queue.html
http://www.2cto.com/kf/201504/395335.html
文章的脚注信息由WordPress的wp-posturl插件自动生成