[英]Asyncio asynchronously run a function
在 python 中,我试图在线程中异步运行异步 function。 我现在的代码是
import time
import asyncio
async def test():
print('Started!')
time.sleep(2)
print('Ok!')
async def main():
loop = asyncio.get_event_loop()
start_time = time.time()
await asyncio.gather(*(loop.run_in_executor(None, test) for i in range(5)))
print("--- %s seconds ---" % (time.time() - start_time))
asyncio.run(main())
但这给了我错误RuntimeWarning: Enable tracemalloc to get the object allocation traceback
。
我也试过
await asyncio.gather(*(asyncio.to_thread(test) for i in range(5)))
但这不适用于阻塞代码(就像我拥有的 time.sleep 一样)。 它只启动一个线程并一个一个地执行 time.sleep。 我该如何解决这个问题?
不要将同步与异步代码混为一谈。 您的test
function 被阻塞并且仅添加async
关键字不会使其异步:
import time
import asyncio
def test():
print("Started!")
time.sleep(2)
print("Ok!")
async def main():
start_time = time.time()
await asyncio.gather(*(asyncio.to_thread(test) for i in range(5)))
print("--- %s seconds ---" % (time.time() - start_time))
if __name__ == "__main__":
asyncio.run(main())
测试:
$ python test.py
Started!
Started!
Started!
Started!
Started!
Ok!
Ok!
Ok!
Ok!
Ok!
--- 2.0036470890045166 seconds ---
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.