【协程】7、asyncio.Future对象
1、concurrent.futures.Future对象
- 使用线程池、进程池实现异步操作时用到的对象。
- 具体参考:2020-11-16 ThreadPoolExecutor 的用法及实战
- 以后写代码可能会存在交叉使用。例如:你的某个项目都是基于协程异步编程,加入mysql不支持协程,那么在访问数据库的时候只能使用线程或进程做异步编程
# -*- coding: utf-8 -*-
import time
import asyncio
import concurrent.futures
def func1():
# 某个耗时操作
time.sleep(2)
return 'SB'
async def main():
loop = asyncio.get_running_loop()
# 1、run in the default loop^s executor(默认ThreadPoolExecutor)
# 第一步:内部会先调用ThreadPoolExecutor的submit方法去线程池中申请一个线程去执行func1函数,并返回一个concurrent.futures。Future对象
# 第二步:调用asyncio.wrap_future将concurrent.futures,Future对象包装为asyncio.Future对象
# 因为concurrent.futures.Future对象不支持await语法,所以需要包装为asyncio.Future对象,才能使用。
fut = loop.run_in_executor(None, func1)
result = await fut
print('default thread pool:', result)
# 2. Run in a custom thread pool:
# with concurrent.futures.ThreadPoolExecutor() as pool:
# result = await loop.run_in_executor(pool, func1)
# print('custom thread pool', result)
# 3. Run in custom process pool:
# with concurrent.futures.ProcessPoolExecutor() as pool:
# result = await loop.run_in_executor(pool, func1)
# print('custom process pool', result)
本文来自博客园,作者:郭祺迦,转载请注明原文链接:https://www.cnblogs.com/guojie-guojie/p/16330256.html

浙公网安备 33010602011771号