How can I catch SIGINT in threading python program? How can I catch SIGINT in threading python program? multithreading multithreading

How can I catch SIGINT in threading python program?


Threads and signals don't mix. In Python this is even more so the case than outside: signals only ever get delivered to one thread (the main thread); other threads won't get the message. There's nothing you can do to interrupt threads other than the main thread. They're out of your control.

The only thing you can do here is introduce a communication channel between the main thread and whatever threads you start, using the queue module. You can then send a message to the thread and have it terminate (or do whatever else you want) when it sees the message.

Alternatively, and it's often a very good alternative, is to not use threads. What to use instead depends greatly on what you're trying to achieve, however.


Basically you can check if the parent issued a signal by reading a queue during the work. If the parent receives a SIGINT then it issues a signal across the queue (in this case anything) and the children wrap up their work and exit...

def fun(arg1, thread_no, queue):   while True:    WpORK...    if queue.empty() is False or errors == 0:     print('thread ', thread_no, ' exiting...')     with open('output_%i' % thread_no, 'w') as f:      for line in lines: f.write(line)     exit()threads = []for i, item in enumerate(items): threads.append( dict() ) q = queue.Queue() threads[i]['queue'] = q threads[i]['thread'] = threading.Thread(target=fun, args=(arg1, i, q)) threads[i]['thread'].start()try: time.sleep(10000)except: for thread in threads:  thread['queue'].put('TERMINATING')