gpt4 book ai didi

Python线程-阻塞操作-终止执行

转载 作者:太空宇宙 更新时间:2023-11-03 17:25:17 24 4
gpt4 key购买 nike

我有一个像这样的Python程序:

from threading import Thread

def foo():
while True:
blocking_function() #Actually waiting for a message on a socket

def run():
Thread(target=foo).start()

run()

该程序不会以 KeyboardInterrupt 终止,由于主线程在线程运行之前退出 foo()有机会终止。我尝试通过运行 while True 来保持主线程处于事件状态。调用 run() 后循环但这也不会退出程序(blocking_function()只是阻止线程运行,我猜,等待消息)。还尝试在主线程中捕获 KeyboardInterrupt 异常并调用 sys.exit(0) - 相同的结果(我实际上希望它杀死运行 foo() 的线程,但显然它没有)

现在,我可以简单地使 blocking_function() 的执行超时。但这并不好玩。我可以解锁KeyboardInterrupt或类似的东西?

主要目标:终止 Ctrl+C 上阻塞线程的程序

最佳答案

也许有一点解决方法,但您可以使用线程而不是线程。这并不是真正的建议,但如果它适合您和您的程序,为什么不呢。

您需要保持程序运行,否则线程在run()之后立即退出

import thread, time

def foo():
while True:
blocking_function() #Actually waiting for a message on a socket

def run():
thread.start_new_thread(foo, ())

run()
while True:
#Keep the main thread alive
time.sleep(1)

关于Python线程-阻塞操作-终止执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32649946/

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