I Am trying to send a signal from a child thread to the main thread in a multi-threaded program (cannot use multi-processes). Unfortunately even after exhausting all the rea
Signals and threads really, really don't play nice together.
Consider use an Event
or other synchronization mechanism. The following example creates an 'event' object, then passes it to two threads. One waits for two seconds, then signals the other to print out a message then exit.
import threading, time
def flagger_thread(event):
"""
wait for two seconds, then make 'event' fire
"""
time.sleep(2)
event.set()
def waiter_thread(event):
print("Waiting for event")
if event.wait(5):
print("event set.")
else:
print("Timed out.")
stop_event = threading.Event()
threading.Thread(target=flagger_thread, args=[stop_event]).start()
threading.Thread(target=waiter_thread, args=[stop_event]).start()
# wait for all threads to exit
for t in threading.enumerate():
if t != threading.current_thread():
t.join()
Waiting for event
event set.