重慶分公司,新征程啟航
為企業提供網站建設、域名注冊、服務器等服務
為企業提供網站建設、域名注冊、服務器等服務
這篇文章主要講解了“python中condition條件變量有什么作用”,文中的講解內容簡單清晰,易于學習與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學習“python中condition條件變量有什么作用”吧!
目前成都創新互聯已為近1000家的企業提供了網站建設、域名、網站空間、成都網站托管、企業網站設計、正定網站維護等服務,公司將堅持客戶導向、應用為本的策略,正道將秉承"和諧、參與、激情"的文化,與客戶和合作伙伴齊心協力一起成長,共同發展。
1、Python提供的Condition對象支持復雜的線程同步。
2、Condition被稱為條件變量,除了提供類似Lock的acquire和release方法外,還提供wait和notify方法。線程先acquire條件變量,然后判斷一些條件。
實例
import threading, time class Hider(threading.Thread): def __init__(self, cond, name): super(Hider, self).__init__() self.cond = cond self.name = name def run(self): time.sleep(1) #確保先運行Seeker中的方法 self.cond.acquire() #b print(self.name + ': 我已經把眼睛蒙上了') self.cond.notify() self.cond.wait() #c #f print(self.name + ': 我找到你了 ~_~') # self.cond.notify() self.cond.release() #g print(self.name + ': 我贏了') #h class Seeker(threading.Thread): def __init__(self, cond, name): super(Seeker, self).__init__() self.cond = cond self.name = name def run(self): self.cond.acquire() self.cond.wait() #a #釋放對瑣的占用,同時線程掛起在這里,直到被notify并重新占有瑣。 #d print(self.name + ': 我已經藏好了,你快來找我吧') self.cond.notify() self.cond.wait() #e #h self.cond.release() print(self.name + ': 被你找到了,哎~~~') cond = threading.Condition() seeker = Seeker(cond, 'seeker') hider = Hider(cond, 'hider') seeker.start() hider.start()
感謝各位的閱讀,以上就是“python中condition條件變量有什么作用”的內容了,經過本文的學習后,相信大家對python中condition條件變量有什么作用這一問題有了更深刻的體會,具體使用情況還需要大家實踐驗證。這里是創新互聯,小編將為大家推送更多相關知識點的文章,歡迎關注!