1、线程池模块
引入
1
|
from concurrent.futures import ThreadPoolExecutor |
2、使用线程池
一个简单的线程池使用案例
1
2
3
4
5
6
7
8
9
10
11
12
13
|
from concurrent.futures import ThreadPoolExecutor import time pool = ThreadPoolExecutor( 10 , 'Python' ) def fun(): time.sleep( 1 ) print ( 1 , end = '') if __name__ = = '__main__' : # 列表推导式 [pool.submit(fun) for i in range ( 20 ) if True ] |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
from concurrent.futures import ThreadPoolExecutor import time pool = ThreadPoolExecutor( 10 , 'Python' ) def fun(arg1,arg2): time.sleep( 1 ) print (arg1, end = ' ' ) print (arg2, end = ' ' ) if __name__ = = '__main__' : # 列表推导式 [pool.submit(fun,i,i) for i in range ( 20 ) if True ] # 单个线程的执行 task = pool.submit(fun, 'Hello' , 'world' ) # 判断任务执行状态 print (f 'task status {task.done()}' ) time.sleep( 4 ) print (f 'task status {task.done()}' ) # 获取结果的函数是阻塞的,所以他会等线程结束之后才会输出 print (task.result()) |
3、获取结果
阻塞等待
1
|
print (task.result()) |
批量获取结果
1
2
|
for future in as_completed(all_task): data = future.result() |
阻塞主线程,等待执行结束再执行下一个业务
1
2
3
|
# 等待线程全部执行完毕 wait(pool.submit(fun, 1 , 2 ),return_when = ALL_COMPLETED) print ('') |
以上就是Python 线程池模块之多线程操作代码的详细内容,更多关于Python 线程池模块的资料请关注服务器之家其它相关文章!
原文链接:https://blog.csdn.net/qq_15071263/article/details/116891521