并发

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

异步:asyncio

  import asyncio
 
  async def say_hi():
      await asyncio.sleep(3)
      print('Hi Python')
 
  async def main():
      tasks = []
      for i in range(20):
          tasks.append(say_hi()) # 添加任务到列表
      await asyncio.gather(*tasks)
 
  asyncio.run(main()) # 运行
  import asyncio
  import time
 
  import httpx
 
  async def get_url(url):
      """获取状态"""
      async with httpx.AsyncClient() as client:
          r = await client.get(url)
          print(r.status_code)
 
  tasks = [get_url('https://google.com') for i in range(42)]
 
  # 方式一
  def task_asyncio1(tasks):
      loop = asyncio.get_event_loop()
      try:
          loop.run_until_complete(asyncio.gather(*tasks))
      finally:
          loop.close()
 
  task_asyncio1(tasks) # 调用
 
  # 方式二
  async def task_asyncio2(takss):
      await asyncio.gather(*tasks)
 
  asyncio.run(task_asyncio2(tasks)) # 调用

参考