什么是协程,一个线程内的多个任务可以互相切换。由此得出我的理解:
- 任务可以暂停
- 任务暂停可以切换到其它任务
- 任务可以从暂停的地方重新执行
yield 就可以实现这样的操作
def coroutine_task1():
print("coroutine_task1 started")
x = yield
print(f"coroutine_task1 received value: {x}")
y = yield x * 2
print(f"coroutine_task1 received value: {y}")
yield y * 3
def coroutine_task2():
print("coroutine_task2 started")
x = yield
print(f"coroutine_task2 received value: {x}")
y = yield x * 2
print(f"coroutine_task2 received value: {y}")
yield y * 3
task1 = coroutine_task1()
task2 = coroutine_task2()
task1.send(None)
task2.send(None)
task1.send(10)
task2.send(10)
task1.send(20)
task2.send(20)
task1.close()
task2.close()
运行结果
coroutine_task1 started
coroutine_task2 started
coroutine_task1 received value: 10
coroutine_task2 received value: 10
coroutine_task1 received value: 20
coroutine_task2 received value: 20
coroutine_task1 运行遇到yield就暂停了,切换到coroutine_task2进行执行了,2个task切换执行
由此引出yield遇到io操作,并且设置一个事件,io等待完成切换回来,在此io等待期间,可以切换到其它任务