用greenlet实现协程消费者生产者

代码:

  from greenlet import greenlet

  import random

  def pro():    生产者

    while True:

      item = random.randint(0,99)

      print("生产了:",item)

      c.switch(item)    向消费者发送item ,并阻塞自己,解阻塞消费者

  def consumer():    消费者

    while True:

      item = p.switch()  用item接收生产者的数据,阻塞自己,解阻塞生产者

      print("消费了:",item)

  p = greenlet(pro)

  c = greenlet(consumer)

  c.switch()    从消费者开始执行

      

原文地址:https://www.cnblogs.com/cxhzy/p/10015554.html