zoukankan      html  css  js  c++  java
  • 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 ~ % 

  • 相关阅读:
    模拟道路交通简单练习(类)
    printf 格式化输出符号
    ffplay源码分析01 ---- 框架
    RTSP协议
    SRS流媒体服务器03 ---- st-thread
    生成aac sdp文件
    生成h264 sdp文件
    RTP分包解包 ---- H264
    RTP协议
    SRS流媒体服务器02 ---- 文件框架
  • 原文地址:https://www.cnblogs.com/sea-stream/p/14057948.html
Copyright © 2011-2022 走看看