我有多個執行緒使用事件物件等待超時。如果我想在事件上呼叫 set(),這將解除對所有執行緒的阻塞。什么是解除阻塞特定執行緒并使其他執行緒處于等待狀態的好方法?
我考慮過不是等待,而是每個執行緒都有一個while回圈,使用全域變數作為條件來指示執行緒何時應該回傳,但是我不確定這如何保持我想要的每個執行緒的超時,沒有檢查時間戳。
import threading
import time
t1 = threading.Thread(target=startTimeout)
t2 = threading.Thread(target=startTimeout)
timeoutEvent = threading.Event()
time.sleep(0.3)
timeoutEvent.set()
# How to have indivial timeoutEvents for specific threads?
def startTimeout():
check = timeoutEvent.wait(1)
if (check):
# set was called
else:
# Timeout
uj5u.com熱心網友回復:
您可以為每個執行緒或一組執行緒創建一個事件,只需將其作為引數傳遞給它們或將其存盤在某處。
import threading
import time
def startTimeout(event):
check = event.wait(1)
if (check):
print('pass')
else:
print("didn't pass")
timeoutEvent1 = threading.Event()
timeoutEvent2 = threading.Event()
t1 = threading.Thread(target=startTimeout,args=(timeoutEvent1,))
t2 = threading.Thread(target=startTimeout,args=(timeoutEvent2,))
t1.start()
t2.start()
time.sleep(0.3)
timeoutEvent1.set()
t1.join()
t2.join()
pass
didn't pass
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/532700.html
標籤:Python多线程
