【整理】Python生产者消费者模型代码

原创文章,转载请注明: 转载自勤奋的小青蛙
本文链接地址: 【整理】Python生产者消费者模型代码

参考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()

参考:http://agiliq.com/blog/2013/10/producer-consumer-problem-in-python/?utm_source=tuicool&utm_medium=referral

https://docs.python.org/3.4/library/queue.html

http://www.2cto.com/kf/201504/395335.html

原创文章,转载请注明: 转载自勤奋的小青蛙
本文链接地址: 【整理】Python生产者消费者模型代码

文章的脚注信息由WordPress的wp-posturl插件自动生成



|2|left
打赏

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: