CTRL + C close Multithreaded Python program

Source: Internet
Author: User

The project often need to use multi-threading, if a Python program with multi-threading, when the child thread does not end, with CTRL + C is not close the main thread, this time can only kill with kill command, this will be very troublesome.

So discussed how to CTRL + C close multi-threaded Python program, but also on the internet to check a lot of other people's practice, did a lot of experiments, and tried many ways, summed up a way to use is that the thread Setdeamon (True), The function of join is realized by IsAlive method.

Code:

#Encoding=utf-8__author__='[email protected]'ImportThreading fromTimeImportSleepdeff (): Sleep (100) P=threading. Thread (target=f) P.setdaemon (True) P.start ()#P.join () while1:    if  notp.isalive (): BreakSleep (1)Print ' Done'

You can use this function when there are a lot of sub-threads

def Threads_join (threads):     " " To     block the main thread, wait for the child thread to finish before continuing, using this method than the advantage of using join, you can    Ctrl + C kill the process "      Threads:        while 1:             if  t.isalive ():                Sleep ( )            Else:                break

The disadvantage of this approach is to make the main thread block, until the sub-thread implementation of this function is too cumbersome to implement, originally with join to achieve a lot of convenience

The following is a study of the process of trying, but all can not realize the function of CTRL + C shutdown

The original multi-threaded

def f ():    sleep (p =threading). Thread (target=f) p.start () p.join ()print'done'

This is the most primitive of a multithreaded program.

Try one: Set the thread as the daemon thread, i.e. join

P.setdaemon (True)

But Ctrl + C, the program does not respond, with no add is the same

Try two: Use the signal, because CTRL C when the system will send SIGINT signal to the program, so we can make the program capture this signal, and call the OS kill method to kill themselves

ImportSignalImportOSImportThreading fromTimeImportSleepdefF (A, B):Print 'Kill me'Os.kill (Os.getpid (), signal. SIGKILL)defTF (): Sleep (20) signal.signal (signal. SIGINT,F) P=threading. Thread (target=TF) P.start () P.join ()Print ' Done'

After the program runs, I immediately press CTRL C, the main thread routines and other sub-thread Sleep20, will print ' Kill me ', to prove that the main thread waiting for the execution of the child thread, that is, when the join, is not able to capture the signal sent by the system, to wait for the child thread execution, to be captured. So this method still does not work.

Try three, with a flag to let the child thread itself end its own run

is_exit=0defF (A, B):Globalis_exit is_exit=1Print 'Kill me'Os.kill (Os.getpid (), signal. SIGKILL)defTF (): while  notIs_exit:sleep (20) signal.signal (signal. SIGINT,F) P=threading. Thread (target=TF) P.start () while1: Sleep (10)Print ' Done'

This adds a flag is_exit is used to flag whether the child thread continues execution, and then joins the signal, when the capture off signal, the is_exit changed to 1, so that the child thread itself ends, because the main thread in the state of the join is not acceptable signal, so here let the main thread is waiting for the state.

This practice is able to do the Ctrl-C shut down the sub-thread, the disadvantage is that the child thread needs to finish a loop to end, and the main thread does not have the function of join, applicable to the main thread after the sub-thread release tasks do not need to do any operation.

So in general, the main reason for CTRL C not to close the multithreaded program is to use the Join method, once the join, the main thread will always be in a blocking state, do not accept any outside contact. But the join method in the actual business is often needed, I looked for a long time did not find the alternative to join, but also can be Ctrl C method. The first program used to use the Alive method to achieve the function of join is not very good, but can not use its solution, I hope to find a better way to implement the join function.

CTRL + C close Multithreaded Python program

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.