【问题标题】:How to stop the multithreaded process by ctrl+cctrl+c如何停止多线程进程
【发布时间】:2014-05-29 06:03:45
【问题描述】:

我试图在执行过程中终止进程,但未能阻止它。

我的线程是无限循环线程在收到终止信号之前不会终止

我只能通过终端上的 kill 命令终止

def signal_handler(*args):
    print("Killed by user")
    teardown()
    sys.exit(0)

def install_signal():
    for sig in (SIGABRT, SIGILL, SIGINT, SIGSEGV, SIGTERM):
        signal(sig, signal_handler)


class Monitor(object):
    ...
    def run(self):
        """Run the monitor thread

        Add the tasks to threads list
        """
        try:
            threads = {
                "streaming": Streaming(
                    self.args["rtsp_link"], 
                    int(self.args["duration"]), 
                    int(self.args["period"])
                ),
                "telnet_vid": p,
                "telnet_aud": c,
            }

            for sub_task in threads.values():
                sub_task.setDaemon(True)
                sub_task.start()

            for sub_task in threads.values():
                sub_task.join()

            time.sleep(1)

            logging.info("Completed Monitor Tasks")

        except KeyboardInterrupt:
            print("Ok ok, quitting")
            sys.exit(1)
        except BaseException as e:
            print("Got BaseException")
            traceback.print_exc(file=sys.stdout)
            raise e

def main():
    try:
        install_signal()
        monitor = Monitor('tests/test_configuration.txt')
        monitor.run()
    except KeyboardInterrupt:
        print("Ok ok, quitting")
        sys.exit(1)

如果我在join() 中添加超时,主线程将不会被阻塞,将在几秒钟内终止,并且不再接收键盘中断

我提到了这个blog

while len(running_threads) > 0 :
    try:
        print("To add join")
        # Join all threads using a timeout so it doesn't block
        # Filter out threads which have been joined or are None
        running_threads = [t.join(1) for t in running_threads if t is not None and t.isAlive()]
    except KeyboardInterrupt:
        print("Ctrl+C received! Sending kill to threads!!!")
        for t in running_threads:
            t.kill_received = True

【问题讨论】:

  • timeout添加到sub_task.join()并调用is_alive()来查看线程是否结束。在 Python 2 上,thread.join() 没有超时可能不会被信号中断。
  • 嗨@J.F.Sebastian 我更新了帖子,它不起作用
  • t.join(1) 总是返回 None 因此running_threads = [t.join(1) for ...] 不正确
  • @J.F.Sebastian 为什么?你说添加一个timeout 加入,所以我添加了1 秒加入。
  • 思考为什么running_threads = [None, None, None, ...] 不是非常有用

标签: multithreading python-2.7


【解决方案1】:

替换:

for sub_task in threads.values():
    sub_task.join() # no timeout

与:

running_threads = threads.values()
while running_threads:
    for t in running_threads:
        t.join(.1) # with timeout
    running_threads = [t for t in running_threads if t.is_alive()]

【讨论】:

    猜你喜欢
    • 2021-12-23
    • 1970-01-01
    • 2018-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-18
    • 1970-01-01
    相关资源
    最近更新 更多