關于python線程池的四種實現(xiàn)方式
python 線程池的四種實現(xiàn)方式
線程簡述
一個程序運行起來后,一定有一個執(zhí)行代碼的東西,這個東西就是線程;
一般計算(CPU)密集型任務適合多進程,IO密集型任務適合多線程;
一個進程可擁有多個并行的(concurrent)線程,當中每一個線程,共享當前進程的資源
以下是對發(fā)現(xiàn)的幾種多線程進行的匯總整理,均已測試運行 多線程實現(xiàn)的四種方式分別是:
multiprocessing下面有兩種:
from multiprocessing.dummy import Pool as ThreadPool # 線程池 from multiprocessing.pool import ThreadPool # 線程池,用法無區(qū)別,唯一區(qū)別這個是線程池
另外兩種:
from concurrent.futures import ThreadPoolExecutor # python原生線程池,這個更主流 import threadpool # 線程池,需要 pip install threadpool,很早之前的
方式1 multiprocessing.dummy Pool()
- 非阻塞方法
multiprocessing.dummy.Pool.apply_async() 和 multiprocessing.dummy.Pool.imap()
線程并發(fā)執(zhí)行
- 阻塞方法
multiprocessing.dummy.Pool.apply()和 multiprocessing.dummy.Pool.map()
線程順序執(zhí)行
from multiprocessing.dummy import Pool as Pool import time def func(msg): print('msg:', msg) time.sleep(2) print('end:') pool = Pool(processes=3) for i in range(1, 5): msg = 'hello %d' % (i) pool.apply_async(func, (msg,)) # 非阻塞,子線程有返回值 # pool.apply(func,(msg,)) # 阻塞,apply()源自內建函數(shù),用于間接的調用函數(shù),并且按位置把元祖或字典作為參數(shù)傳入。子線程無返回值 # pool.imap(func,[msg,]) # 非阻塞, 注意與apply傳的參數(shù)的區(qū)別 無返回值 # pool.map(func, [msg, ]) # 阻塞 子線程無返回值 print('Mark~~~~~~~~~~~~~~~') pool.close() pool.join() # 調用join之前,先調用close函數(shù),否則會出錯。執(zhí)行完close后不會有新的進程加入到pool,join函數(shù)等待所有子進程結束 print('sub-process done')
運行結果:
方式2:multiprocessing.pool ThreadPool Threading()
from multiprocessing.pool import ThreadPool # 線程池,用法無區(qū)別,唯一區(qū)別這個是線程池 from multiprocessing.dummy import Pool as ThreadPool # 線程池 import os import time print("hi outside of main()") def hello(x): print("inside hello()") print("Proccess id: %s" %(os.getpid())) time.sleep(3) return x*x if __name__ == "__main__": p = ThreadPool(5) pool_output = p.map(hello, range(3)) print(pool_output)
運行結果:
方式3:主流ThreadPoolExecutor
from concurrent.futures import ThreadPoolExecutor import threading import time # 定義一個準備作為線程任務的函數(shù) def action(max): my_sum = 0 for i in range(max): print(threading.current_thread().name + ' ' + str(i)) my_sum += i return my_sum # 創(chuàng)建一個包含2條線程的線程池 pool = ThreadPoolExecutor(max_workers=2) # 向線程池提交一個task, 20會作為action()函數(shù)的參數(shù) future1 = pool.submit(action, 20) # 向線程池再提交一個task, 30會作為action()函數(shù)的參數(shù) future2 = pool.submit(action, 30) # 判斷future1代表的任務是否結束 print(future1.done()) time.sleep(3) # 判斷future2代表的任務是否結束 print(future2.done()) # 查看future1代表的任務返回的結果 print(future1.result()) # 查看future2代表的任務返回的結果 print(future2.result()) # 關閉線程池 pool.shutdown()
運行結果:
方式4:threadpool
需要 pip install threadpool
import threadpool def hello(m, n, o): """""" print("m = %s, n = %s, o = %s" % (m, n, o)) if __name__ == '__main__': # 方法1 # lst_vars_1 = ['1', '2', '3'] # lst_vars_2 = ['4', '5', '6'] # func_var = [(lst_vars_1, None), (lst_vars_2, None)] # 方法2 dict_vars_1 = {'m': '1', 'n': '2', 'o': '3'} dict_vars_2 = {'m': '4', 'n': '5', 'o': '6'} func_var = [(None, dict_vars_1), (None, dict_vars_2)] # 定義了一個線程池,表示最多可以創(chuàng)建poolsize這么多線程 pool = threadpool.ThreadPool(2) # 調用makeRequests創(chuàng)建了要開啟多線程的函數(shù),以及函數(shù)相關參數(shù)和回調函數(shù),其中回調函數(shù)可以不寫 requests = threadpool.makeRequests(hello, func_var) [pool.putRequest(req) for req in requests] # 將所有要運行多線程的請求扔進線程池 pool.wait() # 等待所有線程完成工作后退出 """ [pool.putRequest(req) for req in requests]等同于 for req in requests: pool.putRequest(req) """
運行結果:
到此這篇關于關于python線程池的四種實現(xiàn)方式的文章就介紹到這了,更多相關python線程池實現(xiàn)內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Python實戰(zhàn)之生成有關聯(lián)單選問卷
這篇文章主要為大家分享了一個Python實戰(zhàn)小案例——生成有關聯(lián)單選問卷,并且能根據(jù)問卷總分數(shù)生成對應判斷文案結果,感興趣的可以了解一下2023-04-04Python中的__new__與__init__魔術方法理解筆記
這篇文章主要介紹了Python中的__new__與__init__魔術方法理解筆記,需要的朋友可以參考下2014-11-11