Python threading event object – How to notify specific thread?

Question:

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

Asked By: questions1010

||

Answers:

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
Answered By: Ahmed AEK
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.