python多线程并行计算通过向线程池ThreadPoolExe

2022-05-26  本文已影响0人  倪桦

Python的线程池可以有效地控制系统中并发线程的数量。
当程序中需要创建许多生存期较短的线程执行运算任务时,首先考虑使用线程池。线程池任务启动时会创建出最大线程数参数max_workers指定数量的空闲线程,程序只要将执行函数提交给线程池,线程池就会启动一个空闲的线程来执行它。当该函数执行结束后,该线程并不会死亡,而是再次返回到线程池中变成空闲状态,等待执行下一个函数。配合使用with关键字实现任务队列完成后自动关闭线程池释放资源。

线程池的使用场合:

使用线程池来执行线程任务示范脚本:

from concurrent.futures import ThreadPoolExecutor ; from threading import Lock;import time
####################################################################### step.1 创建待执行操作
def FUNC(x,secs):
    time.sleep(secs)   ##模拟耗时运算
    with lock:        ##对运算结果的输出操作上锁,保证输出操作在单线程模式下运行,从而顺序向stdout输出内容
        print( str(x) ,'\t', str(secs))
        with open("demofile.txt", 'a') as f:  #向文件demofile.txt写入数据
            f.write("my reuslt "+str(x)+"\n")

    return(x**x)

####################################################################### step.2 线程池执行任务
worklist=[x for x in range(1,11)]
sleeptime=[22,4,1,1,10,6,1,11,1,4]   

open(f'demofile.txt', 'w').close()   ##creat an empty file for write data
with ThreadPoolExecutor(max_workers=4) as exe: #创建线程池
    lock = Lock()        #create the lock
    print('work.No','','sleeptime')
    __ = exe.map(FUNC,worklist,sleeptime)  #使用map循环向线程池提交任务
    print(">>>>>>>>>>>>>>>>>>>>>>") 
print("All return results : ",[ _ for _ in __ ])  #任务并行执行后的返回结果按照任务的提交顺序返回,而不是按照任务的完成循序返回。
print('FInished !')
#######################################################################    结果输出

demo 输出

work.No  sleeptime
>>>>>>>>>>>>>>>>>>>>>>
3    1
4    1
2    4
7    1
6    6
9    1
5    10
10   4
8    11
1    22
All return results :  [1, 4, 27, 256, 3125, 46656, 823543, 16777216, 387420489, 10000000000]
FInished !

参考材料:

6 Usage Patterns for the ThreadPoolExecutor in Python (superfastpython.com)
Is the ThreadPoolExecutor Thread-Safe (superfastpython.com)

https://blog.csdn.net/weixin_39635567/article/details/110294054
https://blog.csdn.net/weixin_45642669/article/details/123413293

上一篇 下一篇

猜你喜欢

热点阅读