concurrency

2022-03-29

并发

1
- 多线程:threading
2
- 多进程:multiprocessing

异步:asyncio

1
import asyncio
2
3
async def say_hi():
4
await asyncio.sleep(3)
5
print('Hi Python')
6
7
async def main():
8
tasks = []
9
for i in range(20):
10
tasks.append(say_hi()) # 添加任务到列表
11
await asyncio.gather(*tasks)
12
13
asyncio.run(main()) # 运行
1
import asyncio
2
import time
3
4
import httpx
5
6
async def get_url(url):
7
"""获取状态"""
8
async with httpx.AsyncClient() as client:
9
r = await client.get(url)
10
print(r.status_code)
11
12
tasks = [get_url('https://google.com') for i in range(42)]
13
14
# 方式一
15
def task_asyncio1(tasks):
16
loop = asyncio.get_event_loop()
17
try:
18
loop.run_until_complete(asyncio.gather(*tasks))
19
finally:
20
loop.close()
21
22
task_asyncio1(tasks) # 调用
23
24
# 方式二
25
async def task_asyncio2(takss):
26
await asyncio.gather(*tasks)
27
28
asyncio.run(task_asyncio2(tasks)) # 调用

参考