協(xié)程:生產(chǎn)者消費(fèi)者模型

生產(chǎn)者消費(fèi)者:

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) # 啟動(dòng)協(xié)程
    for i in range(10):
        log.info("producer running...")
        model.send(i)

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

動(dòng)態(tài)延時(shí)計(jì)算 斐波那契數(shù)列

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
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容