前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python 系列文章 —— 生产者消费者模型

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

原创
作者头像
玩转编程
修改2022-01-13 10:58:52
2280
修改2022-01-13 10:58:52
举报
文章被收录于专栏:玩转编程
  • 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()

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档