zoukankan      html  css  js  c++  java
  • python (协程)生产者,消费者

    #coding=utf-8
    import gevent
    from gevent.queue import Queue, Empty
    import time
    tasks = Queue(maxsize=4)
     
    def worker(n):
        try:
            while True:
                task = tasks.get(timeout=1) # decrements queue size by 1
                print('Worker %s got task %s' % (n, task))
                gevent.sleep(1)
        except Empty:
            print('Worker %s says:"Quitting time!"' % (n))
     
    def boss():
        """
        Boss will wait to hand out work until a individual worker is
        free since the maxsize of the task queue is 3.
        """
     
        for i in range(1,10):
            tasks.put(i)
        print('Assigned all work in iteration 1')#添加完毕
     
        for i in range(10,20):
            tasks.put(i)
        print('Assigned all work in iteration 2')#添加完毕
    t1=time.time()
    gevent.joinall([
        gevent.spawn(boss),
        gevent.spawn(worker, 'steve'),
        gevent.spawn(worker, 'john'),
        gevent.spawn(worker, 'bob'),
    ])
    print(time.time()-t1)

    输出

    Worker steve got task 1
    Worker john got task 2
    Worker bob got task 3
    Worker steve got task 4
    Worker john got task 5
    Worker bob got task 6
    Assigned all work in iteration 1
    Worker steve got task 7
    Worker john got task 8
    Worker bob got task 9
    Worker steve got task 10
    Worker john got task 11
    Worker bob got task 12
    Worker steve got task 13
    Worker john got task 14
    Worker bob got task 15
    Assigned all work in iteration 2
    Worker steve got task 16
    Worker john got task 17
    Worker bob got task 18
    Worker steve got task 19
    Worker john says:"Quitting time!"
    Worker bob says:"Quitting time!"
    Worker steve says:"Quitting time!"

  • 相关阅读:
    md5加密(4)
    生成短的uuid
    九九乘法
    闰年判断
    初识网络传输
    省选模拟77
    省选模拟76
    省选模拟75
    省选模拟74
    省选模拟73
  • 原文地址:https://www.cnblogs.com/sea-stream/p/10364280.html
Copyright © 2011-2022 走看看