concurrent.futures.Future对象:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
import time from concurrent.futures import Future from concurrent.futures.thread import ThreadPoolExecutor from concurrent.futures.process import ProcessPoolExecutor def func(value): time.sleep(1) print(value) pool = ThreadPoolExecutor(max_workers=5) #创建线程池 # pool = ProcessPoolExecutor(max_workers=5) ##创建进程池 for i in range(10): fut = pool.submit(func,i) #拿一个线程去执行函数,和协程一样都会把值返回给一个future对象,只不过func函数返回的是None print(fut.result()) |

这个future和协程的future差不多都是拿来获取值,一般不会交叉使用
交叉使用例子:
如果基于协程的项目+MySQL(不支持的时候)或者其他第三方模块,这时候会需要用到将不支持协程的东西使用进程或者线程进行异步
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
import time import asyncio import concurrent.futures def func1(): time.sleep(2) #做了一个耗时操作 return "func1" async def main(): loop = asyncio.get_running_loop() #获取当前循环 fut = loop.run_in_executor(None,func1)#返回一个future """ 1、内部会先调用ThreadPoolExecutor的submit方法去线程池中申请一个线程执行func1函数,兵返回一个concurrent.funture.Future对象 2、调用asyncio.wrap_future将concurrent.funture.Future对象包装成为asyncio.Future对象,因为concurrent.funture.Future不支持await,把他包装成asyncio.Future就可以使用await """ result = await fut print("default thread pool",result) asyncio.run(main()) |
