Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I catch SIGINT in threading python program?

When using module threading and class Thread(), I can't catch SIGINT (Ctrl + C in console) can not be caught.

Why and what can I do?

Simple test program:

#!/usr/bin/env python

import threading

def test(suffix):
    while True:
        print "test", suffix

def main():
    for i in (1, 2, 3, 4, 5):
        threading.Thread(target=test, args=(i, )).start()

if __name__ == "__main__":
    main()

When I hit Ctrl + C, nothing happens.

like image 213
Marko Kevac Avatar asked Oct 04 '10 09:10

Marko Kevac


People also ask

How do you capture a Sigint in Python?

You can use the functions in Python's built-in signal module to set up signal handlers in python. Specifically the signal. signal(signalnum, handler) function is used to register the handler function for signal signalnum . Show activity on this post.

How do you communicate between threads in Python?

Perhaps the safest way to send data from one thread to another is to use a Queue from the queue library. To do this, create a Queue instance that is shared by the threads. Threads then use put() or get() operations to add or remove items from the queue as shown in the code given below.

Which method is used to identify a thread in Python?

ident (or threading. currentThread(). ident for Python < 2.6).

How do you use a signal handler in Python?

Python signal handlers are always executed in the main Python thread of the main interpreter, even if the signal was received in another thread. This means that signals can't be used as a means of inter-thread communication. You can use the synchronization primitives from the threading module instead.


1 Answers

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.

like image 81
Thomas Wouters Avatar answered Oct 20 '22 13:10

Thomas Wouters