gpt4 book ai didi

multithreading - 如何通过ctrl + c停止多线程进程

转载 作者:行者123 更新时间:2023-12-03 13:12:41 24 4
gpt4 key购买 nike

我试图在执行过程中终止该进程,但未能将其停止。

我的线程是无限循环线程,直到收到kill信号才会终止

我只能在终端上用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

最佳答案

代替:

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()]

关于multithreading - 如何通过ctrl + c停止多线程进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23074317/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com