Home > OS >  Python threading event object - How to notify specific thread?
Python threading event object - How to notify specific thread?

Time:11-12

I have multiple threads that uses an event object to wait with a timeout. If I wanted to call set() on the event, this would unblock all of the threads. What would be a good way to unblock a specific thread, and leave the other threads in a waiting state?

I've thought about instead of waiting, each thread would have a while loop using a global variable as a condition to signal when the thread should return, however I'm not sure how this could keep the timeout I want for each thread, without checking for timestamps.

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

CodePudding user response:

you can create an event for each thread, or a group of threads, just pass it as argument to them or store it somewhere.

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
  • Related