2025-09-10:仓库迁移
This commit is contained in:
24
7.函数/10.1.补课,协程.py
Normal file
24
7.函数/10.1.补课,协程.py
Normal file
@@ -0,0 +1,24 @@
|
||||
# 这里我们要介绍一下协程的机制,协程是在单个线程内让两个函数交替执行的一种形式
|
||||
# 以著名问题生产者和消费者作为基底进行讨论
|
||||
def consumer():
|
||||
return_str = ''
|
||||
while True:
|
||||
print(1)
|
||||
n = yield return_str
|
||||
if not n:
|
||||
return
|
||||
print("消费者正在消费{}".format(n))
|
||||
return_str = "200 OK"
|
||||
|
||||
def producer(c):
|
||||
next(c)
|
||||
n = 0
|
||||
while n < 5:
|
||||
n = n + 1
|
||||
print("生产者正在生产{}".format(n))
|
||||
return_str = c.send(n)
|
||||
print("消费者收到消息返回{}".format(return_str))
|
||||
c.close()
|
||||
|
||||
con = consumer()
|
||||
producer(con)
|
Reference in New Issue
Block a user