asyncio is a library to write concurrent code using the async/await syntax.
asyncio is used as a foundation for multiple Python asynchronous frameworks that provide high-performance network and web-servers, database connection libraries, distributed task queues, etc.
asyncio is often a perfect fit for IO-bound and high-level structured network code.
asyncio provides a set of high-level APIs to:
run Python coroutines concurrently and have full control over their execution;
perform network IO and IPC;
control subprocesses;
distribute tasks via queues;
synchronize concurrent code;
Additionally, there are low-level APIs for library and framework developers to:
create and manage event loops, which provide asynchronous APIs for networking, running subprocesses, handling OS signals, etc;
implement efficient protocols using transports;
bridge callback-based libraries and code with async/await syntax.
importtimeimportasyncioasyncdefstart_run(delay,name):awaitasyncio.sleep(delay)print('%s start run'%name)asyncdefmain():print(f"started at {time.strftime('%X')}")awaitstart_run(2,'dog')awaitstart_run(3,'cat')print(f"finished at {time.strftime('%X')}")asyncio.run(main())
运行后输出结果如下
1
2
3
4
5
started at 20:15:09
dog start run
cat start run
finished at 20:15:14
importtimeimportasyncioasyncdefstart_run(delay,name):awaitasyncio.sleep(delay)print('%s start run'%name)asyncdefmain():dog_run=asyncio.create_task(start_run(2,'dog'))cat_run=asyncio.create_task(start_run(3,'cat'))print(f"started at {time.strftime('%X')}")awaitdog_runawaitcat_runprint(f"finished at {time.strftime('%X')}")asyncio.run(main())
运行后输出结果如下
1
2
3
4
5
started at 20:19:18
dog start run
cat start run
finished at 20:19:23
提示:暂时别像下面这样操作
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
importtimeimportasyncioasyncdefstart_run(delay,name):awaitasyncio.sleep(delay)print('%s start run'%name)asyncdefmain():print(f"started at {time.strftime('%X')}")awaitasyncio.create_task(start_run(2,'dog'))awaitasyncio.create_task(start_run(3,'cat'))print(f"finished at {time.strftime('%X')}")asyncio.run(main())