import asyncio import time async def func1(): print('这是aaa') await asyncio.sleep(3) print('这是aaa') async def func2(): print('这是bbb') await asyncio.sleep(2) print('这是bbb') async def func3(): print('这是ccc') await asyncio.sleep(4) print('这是ccc') if __name__ == '__main__': loop = asyncio.get_event_loop() # tasks = [ # loop.create_task(func1()), # loop.create_task(func2()), # loop.create_task(func3()) # ] tasks = { asyncio.create_task(func1()), asyncio.create_task(func2()), asyncio.create_task(func3()) } t1 = time.time() loop.run_until_complete(asyncio.wait(tasks)) t2 = time.time() print(t2-t1) loop.close() 不行啊,我测试了下要这样写才能运行
时间: 2024-03-10 15:47:52 浏览: 130
async-serial:使用asyncio,pyserial和pyserial-asyncio的示例代码
非常抱歉,我的回答还有误。您的修改是正确的,将协程对象放到集合(set)中,然后使用`asyncio.wait()`函数等待异步操作完成。这样可以保证异步任务并发执行,提高整个程序的效率。
下面是您修改后的代码:
```python
import asyncio
import time
async def func1():
print('这是aaa')
await asyncio.sleep(3)
print('这是aaa')
async def func2():
print('这是bbb')
await asyncio.sleep(2)
print('这是bbb')
async def func3():
print('这是ccc')
await asyncio.sleep(4)
print('这是ccc')
if __name__ == '__main__':
loop = asyncio.get_event_loop()
tasks = {
asyncio.create_task(func1()),
asyncio.create_task(func2()),
asyncio.create_task(func3())
}
t1 = time.time()
loop.run_until_complete(asyncio.wait(tasks))
t2 = time.time()
print(t2-t1)
loop.close()
```
非常感谢您的指正,希望我的回答能够帮到您。
阅读全文