Operating system OS, Python - Coroutine

stay in the pit

Example 1. Implementing the producer-consumer model with coroutines

  1. Python's support for coroutines is implemented through generators.
  2. Reference: https://blog.csdn.net/pfm685757/article/details/49924099
  3. Reference: https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/001432090171191d05dae6e129940518d1d6cf6eeaaa969000
"""
    1. 用协程实现消费者生产者模型
    2. Python对协程的支持是通过generator实现的
    3. 有yield的话,就是generator
"""

def consumer():
    r = ''
    while True:
        # n为send过来的值
        # yield类似于断点,有两个作用。
        # 1. 生成值
        # 2. 在这里断点,交出控制权。
        n = yield r
        if not n:
            return
        print('[CONSUMER] Consuming %s...' % n)
        r = '200 OK'

def produce(c): 
    #start generator with None
    c.send(None)
    n = 0
    while n < 5:
        n = n + 1
        print('[PRODUCER] Producing %s...' % n)
        #启动生成器,并附带一个值,r接收yield生成的值
        r = c.send(n)
        print('[PRODUCER] Consumer return: %s' % r)
    c.close()

c = consumer()

produce(c)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324844259&siteId=291194637