Python 系列文章 —— 生产者消费者模型

2022-01-13 10:58:52 浏览数 (1)

  • producer_consumer_final_version
代码语言:javascript复制
  import threading
    import time
    import queue

    def consume(thread\_name, q):
        while True:
            time.sleep(2)
            product = q.get()
            print("%s consume %s" % (thread\_name, product))
            q.task\_done()

    def produce(thread\_name, q):
        for i in range(3):
            product = 'product-'   str(i)
            q.put(product)
            print("%s produce %s" % (thread\_name, product))
            time.sleep(1)
        q.join()
                
    q = queue.Queue()
    p = threading.Thread(target=produce, args=("producer",q))
    c = threading.Thread(target=consume, args=("consumer",q))
    c1 = threading.Thread(target=consume, args=("consumer-1",q))

    c.setDaemon(True)
    c1.setDaemon(True)
    p.start()
    c.start()
    c1.start()

    p.join()
  • producer_consumer_simple_version
代码语言:python代码运行次数:0复制
    import threading
    import time
    import queue

    def consume(thread_name, q):
        while True:
            time.sleep(2)
            product = q.get()
            print("%s consume %s" % (thread_name, product))

    def produce(thread_name, q):
        for i in range(3):
            product = 'product-'   str(i)
            q.put(product)
            print("%s produce %s" % (thread_name, product))
            time.sleep(1)
        
                
    q = queue.Queue()
    p = threading.Thread(target=produce, args=("producer",q))
    c = threading.Thread(target=consume, args=("consumer",q))

    p.start()
    c.start()

    p.join()

0 人点赞