Python how to kill threads blocked on queue with signals?

前端 未结 6 1053
既然无缘
既然无缘 2020-12-18 03:30

I start a bunch of threads working on a queue and I want to kill them when sending the SIGINT (Ctrl+C). What is the best way to handle this?

targets = Queue.         


        
6条回答
  •  情歌与酒
    2020-12-18 04:07

    I managed to solve the problem by emptying the queue on KeyboardInterrupt and letting threads to gracefully stop themselves.

    I don't know if it's the best way to handle this but is simple and quite clean.

    targets = Queue.Queue()
    threads_num = 10
    threads = []
    
    for i in threads_num:
        t = MyThread()
        t.setDaemon(True)
        threads.append(t)
        t.start()
    
    while True:
        try:
            # If the queue is empty exit loop
            if self.targets.empty() is True:
                break
    
        # KeyboardInterrupt handler
        except KeyboardInterrupt:
            print "[X] Interrupt! Killing threads..."
            # Substitute the old queue with a new empty one and exit loop
            targets = Queue.Queue()
            break
    
    # Join every thread on the queue normally
    targets.join()
    

提交回复
热议问题