3

I am trying to have a main thread wait for its worker threads to finish using the following code, but when I try to interrupt it with Ctrl+C it doesn't stop

import threading
import sys
exit = threading.Event()

#pass it to the threads

try:
    exit.wait()
    print('Goodbye')
    sys.exit()
except KeyboardInterrupt:
    print('Interrupted')
    sys.exit()

UPDATE Nothing prints. All background threads are daemons.

5
  • 1
    There was a formatting error. Fixed Commented Jul 24, 2018 at 23:27
  • 1
    What platform are you on? On Linux or macOS (unless you're using 3.0-3.1, which are basically broken), I believe all waits on threading objects should be interruptible by signals, and, once it's interrupted, Python will immediately process the SIGINT as a KeyboardInterrupt. But on Windows… I'm not sure how that works, but you may need something more. Commented Jul 24, 2018 at 23:34
  • 1
    Also, I assume the main thread is still blocked on that exit.wait(), and hasn't yet printed Goodbye', right? (Because otherwise, it's already left the try/except block, so obviously the try can't capture the exception.) Commented Jul 24, 2018 at 23:35
  • 1
    Daemon thread or not? Does Interrupted print? Commented Jul 25, 2018 at 1:40
  • I am on Windows. The main thread is still blocked. All my background threads are currently daemons. Commented Jul 25, 2018 at 11:43

1 Answer 1

1
import threading
import sys
import time
exit = threading.Event()

#pass it to the threads

try:
    print("hi")
    time.sleep(20)
    print('Goodbye')
    sys.exit()
except KeyboardInterrupt:
    print('Interrupted')
    sys.exit()

Please try the above statement to test your code. i have tested it and its working fine for me.

As you are using exit.wait() without giving any timeouts, its running for infinite seconds. So please put some time as an agument. Follow the below code:

exit = threading.Event()

#pass it to the threads

try:
    print("hi")
    exit.wait(5)
    print('Goodbye')
    sys.exit()
except KeyboardInterrupt:
    print('Interrupted')
    sys.exit()
Sign up to request clarification or add additional context in comments.

3 Comments

I am trying to have the main thread wait indefinitely unless interrupted, ideally without simply have a while loop running checking for a flag.
Is that possible??
Thats possible if you will use Loops for that. But using Wait() its impossible.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.