用于在另一个线程中的执行异步方法,需要事先构建一个事件循环 loop ,将 loop 放入线程中 run_forever() ,外部通过方法asyncio.run_coroutine_threadsafe(coro, loop) 让 loop 执行异步方法
coro: 异步方法
loop: 事件循环
import asyncio
import threading
import time
async def function():
print("function里面")
return "返回"
def start_loop(loop):
asyncio.set_event_loop(loop)
loop.run_forever()
if __name__ == '__main__':
loop = asyncio.get_event_loop()
threading.Thread(target=start_loop, args=(loop,), daemon=True).start()
res = asyncio.run_coroutine_threadsafe(function(), loop)
print("开始休眠")
time.sleep(3)
print(res.result()) # 可以通过result()获取异步函数的返回值,会阻塞,直到异步函数运行结束
运行结果:
开始休眠
function里面
返回
用于创建一个线程或进程执行同步函数,下列为三种使用情况
创建线程池执行函数,无法获取返回值,属性executor传None,默认创建线程执行
import asyncio
import time
def function():
print("function里面")
return "返回"
if __name__ == '__main__':
loop = asyncio.get_event_loop()
thread_pool_executor = ThreadPoolExecutor()
res = loop.run_in_executor(thread_pool_executor, function)
# res = loop.run_in_executor(None, function) #传None,默认线程,同上
print("开始休眠")
time.sleep(3)
print(res.result())
运行结果:
function里面开始休眠
Traceback (most recent call last):
File "...test2.py", line 18, in
print(res.result())
asyncio.base_futures.InvalidStateError: Result is not set.
创建进程池执行函数,无法获取返回值
import asyncio
import time
from concurrent.futures import ProcessPoolExecutor
def function():
print("function里面")
time.sleep(10)
return "返回"
if __name__ == '__main__':
loop = asyncio.get_event_loop()
process_pool_executor = ProcessPoolExecutor()
res = loop.run_in_executor(process_pool_executor, function)
print("开始休眠")
time.sleep(3)
print(res.result())
运行结果:
开始休眠
function里面
Traceback (most recent call last):
File "...test2.py", line 18, in
print(res.result())
asyncio.base_futures.InvalidStateError: Result is not set.
在异步函数中用await执行,可以获取返回值,但是会变成同步
import asyncio
import time
from concurrent.futures import ThreadPoolExecutor
def function():
print("function里面")
time.sleep(3)
return "返回"
async def main():
loop = asyncio.get_event_loop()
thread_pool_executor = ThreadPoolExecutor()
res = await loop.run_in_executor(thread_pool_executor, function)
return res
if __name__ == '__main__':
res = asyncio.run(main())
print(res)
运行结果:
function里面
返回