python 协程运行在线程上
run_in_executor asyncio.create_task
import asyncio
from concurrent.futures import ThreadPoolExecutor
def run(cron, *args):
loop = asyncio.new_event_loop()
try:
asyncio.set_event_loop(loop)
return loop.run_until_complete(cron(*args))
finally:
loop.close()
async def main():
loop = asyncio.get_event_loop()
executor = ThreadPoolExecutor(max_workers=5)
futures = []
for x in range(10):
futures.append(
loop.run_in_executor(
executor, run, asyncio.sleep, 1, x
)
)
print(await asyncio.gather(*futures))
if __name__ == '__main__':
asyncio.run(main())
本文来自博客园,作者:vx_guanchaoguo0,转载请注明原文链接:https://www.cnblogs.com/guanchaoguo/p/18400756

浙公网安备 33010602011771号