python多執行緒 多程序

2021-10-06 10:07:26 字數 2152 閱讀 3855

background task -->once join() is used , whether deamon attribute is true is not importantonly useful when the main program is running

ok to kill

starmap和map的區別 :後者本來是只能給函式傳入乙個引數的,前者就是為了彌補這項功能上的缺失才出現的api。但其實後者可以通過把多個引數打包的方式進行引數傳遞。所以感覺前者也沒有多大的不可替代性。

.start(

).run(

).join(

)

pool= mp.pool( poolsize:

int=0)

# 0 means use all cpu

results =

# method 1

results = pool.

map( target , args:iterable of tuples )

for res in results :

print

(res)

# method 2

for i in

range

( x ):)

# 非阻塞

(target , args:

tuple))

# 阻塞

pool.close(

)# 關閉程序池,表示不能在往程序池中新增程序

pool.join(

)# 等待程序池中的所有程序執行完畢,必須在close()/terminate()之後呼叫

for res in results :

print

(res.get())

# 注意這裡的get哦,因為這裡返回的是乙個結果物件

也有第三種方法就是pool.map(func, iterable[, chunksize]),它會使程序阻塞與此直到結果返回

map_async是非阻塞的

process類的建構函式

init(self, group=none, target=none, name=none, args=(), kwargs={})

python3廢棄了原來的thread模組,換成了高階的threading模組,concurrent.futures是使用執行緒的最新方式。(python3把thread模組重新命名為_thread,以此強調這是低層實現, 不應該在應用**中使用)如果使用場景較複雜,需要更高階的工具multiprocessing模組和threading模組。

concurrent.futures是python3新增加的乙個庫,用於併發處理,提供了多執行緒和多程序的併發功能

類似於其他語言裡的執行緒池(也有乙個程序池),他屬於上層的封裝,對於使用者來說,不用在考慮那麼多東西了。

import os

from concurrent import futures

import time

# print(os.cpu_count())

deftest

(num)

: time.sleep(

10-num)

return num

data=[1

,5,9

]with futures.processpoolexecutor(max_workers=os.cpu_count())

as executor:

for future in executor.

map(test,data)

:print

(future)

看了原始碼 以後易知,map是呼叫父類(抽象類)的map函式,which呼叫子類的submit函式,which順序保持不變,但是幾個任務是並行執行的。所以返回的列表的res對應順序跟傳入的是一致的。

python多執行緒 多程序

threading相對與thread是更高階別的執行緒管理模組 thread和threading模組中的一些屬性會有衝突 thread模組擁有的同步原因實際上只有乙個lock,而threading有很多 lock,semaphore等 使用thread模組執行緒,當主線程結束時其子執行緒也會被強制結...

python多執行緒多程序

執行緒等待,多執行緒在執行的時候,每個執行緒都是獨立執行的,不受其他的執行緒干擾,如果想在哪個執行緒執行完之後,再做其他操作的話,就得等待它完成,那怎麼等待呢,使用join,等待執行緒結束 for t in threads 等待3個子執行緒 t.join 主線程等待子執行緒 end time tim...

python 多執行緒多程序

多執行緒,適用於io密集型任務 多程序,適用於cpu密集型任務 資料分析,演算法,依賴cpu來運算 程序就是多個資源的集合,執行緒是包含在程序裡面的,執行緒和執行緒直接是相對獨立的 執行緒的優點 1.易於排程。2.提高併發性。通過執行緒可方便有效地實現併發性。程序可建立多個執行緒來執行同一程式的不同...