当前位置:   article > 正文

python中的wait和gather的用处和区别_协程的wait和gather区别

协程的wait和gather区别

python中的wait和gather的用处和区别

asyncio中的wait和gather的用处和区别
wait等待协程执行完成后才会执行下一句

import asyncio
async def get_html(url):
    print(f'start get {url}')
    await asyncio.sleep(2)
    print(f'end get {url}')


if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    tasks = [get_html("https://www.baidu.com") for i in range(10)]
    loop.run_until_complete(asyncio.wait(tasks))
    loop.close()

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

gather的用法和区别

import asyncio

async def get_html(url):
    print(f'start get {url}')
    await asyncio.sleep(2)
    print(f'end get {url}')


if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    group1 = [get_html("https://www.baidu.com") for i in range(10)]
    group2 = [get_html("https://www.google.com") for i in range(8)]
    group1 = asyncio.gather(*group1)
    group2 = asyncio.gather(*group2)
    loop.run_until_complete(asyncio.gather(group1, group2))
    loop.close()

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

gather更加high-level,gather可以将tasks分组

本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号