Python线程-阻塞操作-终止执行
我有一个类似这样的python程序:Python线程-阻塞操作-终止执行,python,multithreading,Python,Multithreading,我有一个类似这样的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() 由于主线程在运行foo()的线程有机会终止之前退出,因此此程序不会以键盘中断终止。在调用run()后,我尝试通过运行来
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()
由于主线程在运行foo()
的线程有机会终止之前退出,因此此程序不会以键盘中断
终止。在调用run()
后,我尝试通过运行来保持主线程的活动状态,而True则在调用run()
后循环,但这也不会退出程序(blocking_function()
我猜只是阻止线程运行,等待消息)。还尝试在主线程中捕获KeyboardInterrupt异常并调用sys.exit(0)
-相同的结果(我实际上希望它杀死运行foo()
的线程,但显然它没有)
现在,我可以简单地暂停执行阻塞函数()
,但这并不有趣。我可以在键盘中断
或任何类似的设备上解除锁定吗
主要目标:在Ctrl+C
上使用阻塞线程终止程序可能需要一点解决方法,但您可以使用thread
而不是threading
。这并不是真正的建议,但如果它适合你和你的计划,为什么不呢
您需要保持程序运行,否则线程将在run()之后立即退出
它现在确实以Ctrl+C终止。但是为什么thread
这样做而不是threading
??
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)