我正在嘗試用 python 實現多線程程序,但遇到了麻煩。我嘗試設計一個程序,當程序(主線程)接收到特定命令時,程序的計數器會返回到之前的數字并繼續倒計數。以下是我嘗試編寫的代碼: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恢復時從頭開始而不是從阻塞點開始關于問題1,我嘗試在print(count)命令之前添加條件檢查,但是如果我在程序輸出count時輸入“pre”命令,程序仍然會執行count+=1之后,程序會返回到檢查條件并阻止t1,但這并沒有達到我想要的同步效果。有辦法實現這個目標嗎?問題2與問題1類似。我希望每當我輸入命令時,我的程序都會像這樣輸出。1234pre34...但如果t1在執行完print(count)指令后被阻塞,當事件清除后,t1將從count+=1開始繼續執行,所以輸出將變成以下1234pre45...我嘗試在網上查找信息,但始終不知道如何添加關鍵字。有沒有方法或庫可以實現這個功能?我已盡力描述我的問題,但可能還不夠好。如果我對我的問題有任何疑問,我可以添加更多解釋。
2 回答

天涯盡頭無女友
TA貢獻1831條經驗 獲得超9個贊
線程模塊有一個等待方法,該方法將阻塞直到調用notify或notify_all 。這應該可以完成您在第一個問題中尋找的內容。對于問題 2,您可以定義一個處理退出情況的函數,或者只是重新創建一個線程以從頭開始。

largeQ
TA貢獻2039條經驗 獲得超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()
添加回答
舉報
0/150
提交
取消