How to send a signal to the main thread in python without using join?

前端 未结 1 1684
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-13 14:58

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

相关标签:
1条回答
  • 2021-01-13 15:09

    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.

    source

    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()
    

    output

    Waiting for event
    event set.
    
    0 讨论(0)
提交回复
热议问题