最近中文字幕高清中文字幕无,亚洲欧美高清一区二区三区,一本色道无码道dvd在线观看 ,一个人看的www免费高清中文字幕

為了賬號安全,請及時綁定郵箱和手機(jī)立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何使用Python線程監(jiān)聽事件

如何使用Python線程監(jiān)聽事件

倚天杖 2023-12-12 21:44:45
我正在嘗試用 python 實現(xiàn)多線程程序,但遇到了麻煩。我嘗試設(shè)計一個程序,當(dāng)程序(主線程)接收到特定命令時,程序的計數(shù)器會返回到之前的數(shù)字并繼續(xù)倒計數(shù)。以下是我嘗試編寫的代碼:import threadingimport timecount = 0preEvent = threading.Event()runEvent = threading.Event()runEvent.set()preEvent.clear()def pre():    global count    while True:        if event.isSet():            count -= 1            event.clear()def doSomething():    global count    while True:        # if not runEvent.isSet():        #   runEvent.wait()        print(count)        count += 1        time.sleep(1)def main():    t1 = threading.Thread(target=pre, args=())    t2 = threading.Thread(target=doSomething, args=())    t1.start()    t2.start()    command = input("input command")    while command != 'quit':        command = input("input command")        if command == 'pre':            preEvent.set()main()但我遇到了一些問題如何在輸入特定命令時同時阻止 t1如何在t1恢復(fù)時從頭開始而不是從阻塞點(diǎn)開始關(guān)于問題1,我嘗試在print(count)命令之前添加條件檢查,但是如果我在程序輸出count時輸入“pre”命令,程序仍然會執(zhí)行count+=1之后,程序會返回到檢查條件并阻止t1,但這并沒有達(dá)到我想要的同步效果。有辦法實現(xiàn)這個目標(biāo)嗎?問題2與問題1類似。我希望每當(dāng)我輸入命令時,我的程序都會像這樣輸出。1234pre34...但如果t1在執(zhí)行完print(count)指令后被阻塞,當(dāng)事件清除后,t1將從count+=1開始繼續(xù)執(zhí)行,所以輸出將變成以下1234pre45...我嘗試在網(wǎng)上查找信息,但始終不知道如何添加關(guān)鍵字。有沒有方法或庫可以實現(xiàn)這個功能?我已盡力描述我的問題,但可能還不夠好。如果我對我的問題有任何疑問,我可以添加更多解釋。
查看完整描述

2 回答

?
天涯盡頭無女友

TA貢獻(xiàn)1831條經(jīng)驗 獲得超9個贊

線程模塊有一個等待方法,該方法將阻塞直到調(diào)用notify或notify_all 。這應(yīng)該可以完成您在第一個問題中尋找的內(nèi)容。對于問題 2,您可以定義一個處理退出情況的函數(shù),或者只是重新創(chuàng)建一個線程以從頭開始。



查看完整回答
反對 回復(fù) 2023-12-12
?
largeQ

TA貢獻(xiàn)2039條經(jīng)驗 獲得超8個贊

簡單地說,它可以像這樣工作,也許有幫助。


from threading import Thread, Event


count = 0

counter = Event()


def pre():


    global count

    counter.wait()

    count -= 1

    print(count)


def main():


    global count

    print(count)

    while True:

        command = input("Enter 1 to increase, Enter 2 to decrease :")

        if command == "1":

            t1 = Thread(target=pre, args=())

            t1.start()

            counter.set()

        else :

            count += 1

            print(count)



main()


查看完整回答
反對 回復(fù) 2023-12-12
  • 2 回答
  • 0 關(guān)注
  • 261 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號