asyncdefmain(): """ create_task在python3.7加入,python3.7之前可用asyncio.ensure_future()函数; asyncio.create_task只能在协程函数中调用,因为这个函数中需要用到事件循环(event_loop); 如果使用的是 asyncio.gather创建协程对象,那么await的返回值就是协程运行的结果; """ # tasks = [asyncio.create_task(test(i)) for i in range(10)] # result = await asyncio.gather(*tasks)
""" gather接收的参数可以是task或者协程对象,而wait不可以直接接收协程对象 gather返回值的顺序是按照原始顺序排列 """ result = await asyncio.gather(*[test(i) for i inrange(10)]) print(result)
""" 如果使用的是 asyncio.wait,那么返回值是(已完成任务,等待中任务)的集合 """ # tasks = [asyncio.create_task(test(i)) for i in range(10)] # done, pending = await asyncio.wait(tasks) # for task in done: # print(task.result())
defmain2(): """ 通过event_loop执行协程函数 :return: """ loop = asyncio.get_event_loop() tasks = asyncio.gather(*[test(i) for i inrange(10)]) result = loop.run_until_complete(tasks) print(result)