import asyncio
import time
async def say_after(delay, what):
await asyncio.sleep(delay)
print(what)
async def main():
print(f"started at {time.strftime('%X')}")
await say_after(1, 'hello')
await say_after(2, 'world')
print(f"finished at {time.strftime('%X')}")
asyncio.run(main())
output:
started at 17:13:52
hello
world
finished at 17:13:55
async def main():
task1 = asyncio.create_task(
say_after(1, 'hello'))
task2 = asyncio.create_task(
say_after(2, 'world'))
print(f"started at {time.strftime('%X')}")
# Wait until both tasks are completed (should take
# around 2 seconds.)
await task1
await task2
print(f"finished at {time.strftime('%X')}")
Note that expected output now shows that the snippet runs 1 second faster than before: output:
started at 17:14:32
hello
world
finished at 17:14:34
可以看出 task 比 coroutine 快了一秒,也就是 python 是同步执行多个 task 的, 我知道 coroutine 只有一个操作系统线程,yield 来 yield 去,那么 asyncio 是怎么实现 task 的, 有同步问题么?(即一个 task 访问修改一个数据结构,另一个 task 同时访问修改该数据结构, 会 corrupt 该数据结构么?)