python3 生产者消费者(守护线程)

code

from queue import Queue
from threading import Thread

class Producer(Thread):
    def __init__(self, q):
        super().__init__()
        self.count = 5
        self.q = q

    def run(self):
        while self.count > 0:
            print("生产")
            if self.count == 1:
                self.count -= 1
                self.q.put(2)
            else:
                self.count -= 1
                self.q.put(1)


class Consumer(Thread):

    def __init__(self, q):
        super().__init__()
        self.q = q

    def run(self):
        while True:
            print("消费")
            data = self.q.get()
            if data == 2:
                print("stop because data=", data)
                # 任务完成,从队列中清除一个元素
                self.q.task_done()
                break
            else:
                print("data is good,data=", data)
                # 任务完成,从队列中清除一个元素
                self.q.task_done()

if __name__ == '__main__':
    q = Queue()
    p = Producer(q)
    c = Consumer(q)
    p.setDaemon(True)
    c.setDaemon(True)
    p.start()
    c.start()
    # 等待队列清空
    p.join()
    c.join()
    print("queue is complete")

输出

macname@MacdeMBP ~ % python -u "/Users/macname/Desktop/test.py"
生产
生产
消费
生产
生产
生产
data is good,data= 1
消费
data is good,data= 1
消费
data is good,data= 1
消费
data is good,data= 1
消费
stop because data= 2
queue is complete
macname@MacdeMBP ~ % 

原文地址:https://www.cnblogs.com/sea-stream/p/14057948.html