在python中多執行緒可以使用threading來實現,但實際使用時考慮效能等,大多會使用到執行緒池,下面就是基於python2和python3來說明下執行緒池的使用。
import time
def testthread(fl):
time.sleep(1)
print("print:"+fl)
return fl
python2
from multiprocessing import pool #引入pool
lst = #引數列表
pool = pool(3) #設定執行緒池大小
pool.map(testthread, lst) #設定執行的函式及引數
pool.close() #禁止吸入執行緒池
pool.join() #開始執行
python3
from concurrent.futures import threadpoolexecutor, as_completed #引入
lst = #引數列表
executor = threadpoolexecutor(max_workers=3) #設定執行緒池大小
all_task = [executor.submit(testthread, (fl)) for fl in lst] #設定執行緒執行的函式及引數
for future in as_completed(all_task): #執行執行緒
data = future.result() #等待執行方法的返回值,便於後續處理
個人使用下來感覺python3的執行緒池好一點,但python2的應用比較廣,在無法更新python版本的情況下,也只能用python2的方法搞定。
python 執行緒 多執行緒 執行緒池
首先,導入庫 from concurrent.futures import threadpoolexecutor import timewith threadpoolexecutor 1 as executor2 開啟1個執行緒,需要跟括號的1對應 executor2.submit sayhello...
python佇列執行緒池 Python多執行緒與佇列
多執行緒爬蟲對比單執行緒爬蟲有很大的優勢,雖然python中的多執行緒並不是真正意義上的多執行緒,執行緒不可以同時執行,而是順序序列執行的,只是在乙個執行緒在等待時,cpu切換到另外乙個執行緒接著幹活,這樣看起來就感覺像是並行。雖然如此,多執行緒的效率仍然比單執行緒快上很多倍,是爬蟲中不可缺少的技能...
多執行緒 執行緒池
第一 降低資源消耗。通過重複利用已建立的執行緒降低執行緒建立和銷毀造成的消耗。第二 提高響應速度。當任務到達時,任務可以不需要等到執行緒建立就能立即執行。第三 提高執行緒的可管理性。執行緒是稀缺資源,如果無限制地建立,不僅會消耗系統資源,還會降低系統的穩定性,使用執行緒池可以進行統一分配 調優和監控...