Terminate a multi-thread python program

前端 未结 7 771
猫巷女王i
猫巷女王i 2020-12-02 16:17

How to make a multi-thread python program response to Ctrl+C key event?

Edit: The code is like this:

import threading
current = 0

c         


        
7条回答
  •  既然无缘
    2020-12-02 16:54

    I would rather go with the code proposed in this blog post:

    def main(args):
    
        threads = []
        for i in range(10):
            t = Worker()
            threads.append(t)
            t.start()
    
        while len(threads) > 0:
            try:
                # Join all threads using a timeout so it doesn't block
                # Filter out threads which have been joined or are None
                threads = [t.join(1000) for t in threads if t is not None and t.isAlive()]
            except KeyboardInterrupt:
                print "Ctrl-c received! Sending kill to threads..."
                for t in threads:
                    t.kill_received = True
    

    What I have changed is the t.join from t.join(1) to t.join(1000). The actual number of seconds does not matter, unless you specify a timeout number, the main thread will stay responsive to Ctrl+C. The except on KeyboardInterrupt makes the signal handling more explicit.

提交回复
热议问题