首頁  >  文章  >  後端開發  >  python如何切換線程

python如何切換線程

anonymity
anonymity原創
2019-06-18 10:39:564390瀏覽

條件物件能讓一個執行緒 A 停下來,等待其他執行緒 B ,執行緒 B 滿足了某個條件後通知(notify)執行緒 A 繼續運行。線程首先取得一個條件變數鎖,如果條件不足,則該線程等待(wait)並釋放條件變數鎖,如果滿足就執行線程,也可以通知其他狀態為 wait 的線程。其他處於 wait 狀態的執行緒接到通知後會重新判斷條件。 

python如何切換線程

下面為有趣的範例

import threading
class Boy(threading.Thread):
    def __init__(self, cond, name):
        super(Boy, self).__init__()
        self.cond = cond
        self.name = name
    def run(self):
        self.cond.acquire()
        print(self.name + ": 嫁给我吧!?")
        self.cond.notify()  # 唤醒一个挂起的线程,让hanmeimei表态
        self.cond.wait()  # 释放内部所占用的琐,同时线程被挂起,直至接收到通知被唤醒或超时,等待hanmeimei回答
        print(self.name + ": 我单下跪,送上戒指!")
        self.cond.notify()
        self.cond.wait()
        print(self.name + ": Li太太,你的选择太明治了。")
        self.cond.release()
class Girl(threading.Thread):
    def __init__(self, cond, name):
        super(Girl, self).__init__()
        self.cond = cond
        self.name = name
    def run(self):
        self.cond.acquire()
        self.cond.wait()  # 等待Lilei求婚
        print(self.name + ": 没有情调,不够浪漫,不答应")
        self.cond.notify()
        self.cond.wait()
        print(self.name + ": 好吧,答应你了")
        self.cond.notify()
        self.cond.release()
cond = threading.Condition()
boy = Boy(cond, "LiLei")
girl = Girl(cond, "HanMeiMei")
girl.start()
boy.start()

運行結果如下:

LiLei: 嫁给我吧!?
HanMeiMei: 没有情调,不够浪漫,不答应
LiLei: 我单下跪,送上戒指!
HanMeiMei: 好吧,答应你了
LiLei: Li太太,你的选择太明治了。

以上是python如何切換線程的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn