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.
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.
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.
ident (or threading. currentThread(). ident for Python < 2.6).
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With