协程配合线程
asyncio.run_coroutine_threadsafe
该方法的语法如下:
asyncio.run_coroutine_threadsafe(coro, loop)
其实在协程中也可以使用多线程,有时候我们需要在主线程中启动一个子线程去做别的任务,这个时候我们就要用到下面的方法了,先上一个流畅的Python中的代码。
import time
import asyncio
from threading import Thread
now = lambda: time.time()
def start_loop(loop):
asyncio.set_event_loop(loop)
loop.run_forever()
async def do_some_work(x):
print(f'Waiting {x}')
await asyncio.sleep(x)
print(f'Done after {x}s')
def more_work(x):
print(f'More work {x}')
time.sleep(x)
print('Finished more work {x}')
start = now()
# 主线程中创建一个 new_loop
new_loop = asyncio.get_event_loop()
# 创建子线程 在其中开启无限事件循环
t = Thread(target=start_loop, args=(new_loop,))
t.start()
print(f'TIME: {time.time() - start}')
# 在主线程中新注