Python 多工 執行緒同步

2021-10-02 10:10:40 字數 3517 閱讀 7035

高階程式設計技巧 學習筆記

1.1、實現兩個執行緒一問一答

class

xiaoai

(threading.thread)

:def

__init__

(self)

:super()

.__init__(name=

'小艾同學'

)def

run(self)

:print

(f": 在"

)print

(f": 你猜現在幾點了?"

)class

tianmao

(threading.thread)

:def

__init__

(self)

:super()

.__init__(name=

'天貓精靈'

)def

run(self)

:print

(f": 小艾同學"

)print

(f": 現在幾點了?"

)if __name__ ==

'__main__'

: xiaoai = xiaoai(

) tianmao = tianmao(

)

tianmao.start(

) xiaoai.start(

)

想要的結果:

天貓精靈: 小艾同學

小艾同學: 在

天貓精靈: 現在幾點了?

小艾同學: 你猜現在幾點了?

實際的結果:

天貓精靈: 小艾同學

天貓精靈: 現在幾點了?

小艾同學: 在

小艾同學: 你猜現在幾點了?

1.2、condition 解決

wait(self, timeout=none)執行緒等待被喚醒

notify(self, n=1)喚醒某在等待的執行緒

notify_all(self)喚醒所有在等待的執行緒

wait_for(self, predicate, timeout=none)等待背某執行緒喚醒

import threading

class

xiaoai

(threading.thread)

:def

__init__

(self, cond)

:super()

.__init__(name=

'小艾同學'

) self.cond = cond

defrun(self)

:# self.cond.acquire()

with self.cond:

self.cond.wait(

)print

("{}:在"

.format

(self.name)

) self.cond.notify(

) self.cond.wait(

)print

("{}:你猜猜現在幾點了"

.format

(self.name)

) self.cond.notify(

)# self.cond.release()

class

tianmao

(threading.thread)

:def

__init__

(self, cond)

:super()

.__init__(name=

'天貓精靈'

) self.cond = cond

defrun(self)

:# self.cond.acquire()

with self.cond:

print

(f": 小艾同學"

) self.cond.notify(

) self.cond.wait(

)print

(f": 現在幾點了?"

) self.cond.notify(

) self.cond.wait(

)# self.cond.release()

if __name__ ==

'__main__'

: cond = threading.condition(

) xiaoai = xiaoai(cond)

tianmao = tianmao(cond)

xiaoai.start(

) tianmao.start(

)

import threading

class

xiaoai

(threading.thread)

:def

__init__

(self, cond)

:super()

.__init__(name=

'小艾同學'

) self.cond = cond

defrun(self)

:with self.cond:

print

(f": 在"

) self.cond.notify(

) self.cond.wait(

)print

(f": 你猜現在幾點了?"

)class

tianmao

(threading.thread)

:def

__init__

(self, cond)

:super()

.__init__(name=

'天貓精靈'

) self.cond = cond

defrun(self)

:with self.cond:

print

(f": 小艾同學"

) self.cond.wait(

)print

(f": 現在幾點了?"

) self.cond.notify(

)if __name__ ==

'__main__'

: cond = threading.condition(

) xiaoai = xiaoai(cond)

tianmao = tianmao(cond)

tianmao.start(

) xiaoai.start(

)

python多工 執行緒

併發 指的是任務數多餘cpu核數,通過作業系統的各種任務排程演算法,實現用多個任務 一起 執行 實際上總有一些任務不在執行,因為切換任務的速度相當快,看上去一起執行而已 並行 指的是任務數小於等於cpu核數,即任務真的是一起執行的 執行緒python的thread模組是比較底層的模組,python的...

多工 同步

實現多工之間通訊的最簡便的辦法是使用共享的資料結構。雖然共享資料區簡化了任務間的通訊,但是必須保證 每個任務在處理共享資料時的排他性。以避免競爭和資料破壞。共享資源滿足互斥性的一般方法有 1.關中斷,開中斷 2.使用測試並置位指令 3.禁止做任務切換 4.利用訊號量 一.關中斷 開中斷 這估計是最簡...

python 多工 執行緒(一)

python提供了兩個模組來實現多執行緒thread和threading 推薦 thread模組提供了基本的執行緒和鎖支援,threading提供的是更高階的完全的執行緒管理,且更方便操作。在 python3 中不能再使用 thread 模組。為了相容性,python3 將 thread 重新命名為...