Colin Sergi
Colin Sergi

Reputation: 134

Python 3 KeyboardInterrupt Multithreading

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.

Upvotes: 3

Views: 587

Answers (1)

Nitikesh Pattanayak
Nitikesh Pattanayak

Reputation: 84

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

Upvotes: 1

Related Questions