How to interrupt a multithreaded python application?

I am trying to run the following code (it is a bit simplified):

def RunTests(self):
        from threading import Thread
        import signal

        global keep_running
        keep_running = True
        signal.signal( signal.SIGINT, stop_running )

        for i in range(0, NumThreads):
            thread = Thread(target = foo)
            self._threads.append(thread)
            thread.start()

# wait for all threads to finish
        for t in self._threads:
            t.join()

def stop_running(signl, frme):  
    global keep_testing
    keep_testing = False 
    print "Interrupted by the Master. Good by!"
    return 0 

def foo(self):

    global keep_testing

    while keep_testing:
        DO_SOME_WORK();

I expect the user to press Ctrl + C, the program will print a good and message. However, this will not work. Where is the problem?

thank

+3
source share
2 answers

, Python, , - . "join()" - , . , , , / . , , . 'join()' :

while keep_testing:
    signal.pause()
+3

:

" ". , Python , . . .

thread.daemon = True start() , .

0

Source: https://habr.com/ru/post/1771912/


All Articles