首页 > 系统相关 >Python使用事件循环创建线程池和进程池

Python使用事件循环创建线程池和进程池

时间:2022-09-24 16:13:23浏览次数:50  
标签:task 自定义 Python 创建 线程 result func 运行

1、来源参考

参考官方文档示例 :https://docs.python.org/3.9/library/asyncio-eventloop.html#asyncio.loop.run_in_executor

2、代码示例

 1 # -*- coding: utf-8 -*-
 2 """
 3    File Name : test
 4    Description :
 5    Author : Administrator
 6    date : 2022/9/24
 7    Change Activity : 2022/9/24:
 8 """
 9 import concurrent.futures
10 import time
11 import asyncio
12 
13 
14 def task_func():
15     time.sleep(3)
16     return 'task_func finish'
17 
18 
19 async def main():
20     # 获取当前的事件循环对象
21     loop = asyncio.get_running_loop()
22 
23     # 事件循环,使用线程池运行任务
24     future_obj = loop.run_in_executor(None, task_func)
25     result = await future_obj
26     print('默认使用线程池运行,运行结果:', result)
27 
28     # 自定义线程池,使用事件循环执行
29     with concurrent.futures.ThreadPoolExecutor() as pool:
30         future_obj = loop.run_in_executor(pool, task_func)
31         result = await future_obj
32         print('自定义使用线程池运行,运行结果:', result)
33 
34     # 自定义进程池,使用事件循环执行
35     with concurrent.futures.ProcessPoolExecutor() as pool:
36         future_obj = loop.run_in_executor(pool, task_func)
37         result = await future_obj
38         print('自定义进程运行,运行结果:', result)
39 
40 
41 if __name__ == '__main__':
42     asyncio.run(main())

3、运行结果

默认使用线程池运行,运行结果: task_func finish
自定义使用线程池运行,运行结果: task_func finish
自定义进程运行,运行结果: task_func finish

4、总结:

主要用于使用事件循环来创建线程池或进程池运行

 

标签:task,自定义,Python,创建,线程,result,func,运行
From: https://www.cnblogs.com/ygbh/p/16725810.html

相关文章