Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python线程-阻塞操作-终止执行_Python_Multithreading - Fatal编程技术网

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()后,我尝试通过运行来

我有一个类似这样的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()
后,我尝试通过运行
来保持主线程的活动状态,而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)