协程:生产者消费者模型

生产者消费者:

import logging
import time

logging.basicConfig(level = logging.DEBUG)
log = logging.getLogger(__file__)


def consumer():
    log.info("consumer start")
    while True:
        flag = yield
        log.info("running now: %s" %flag)
        time.sleep(1)

def producer(model):
    model.send(None) # 启动协程
    for i in range(10):
        log.info("producer running...")
        model.send(i)

if __name__ == "__main__":
    aa = consumer()
    producer(aa)

动态延时计算 斐波那契数列

import time
import random

def fib(n, start):
    index = 0
    a = 0
    b = 1
    start = start
    while index < n:
        sleep_cnt = yield start
        print("let me think {} seconds".format(sleep_cnt))
        time.sleep(sleep_cnt)
        a, b = b, a + b
        index += 1
        start -= 1

print("test yield send")
N = 20

sfib = fib(N, 11)
res = next(sfib)

while True:
    print(res)
    try:
        res = sfib.send(random.uniform(0, 0.5) * 10)
    except StopIteration:
        break

你可能感兴趣的:(协程:生产者消费者模型)