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

标签 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()

该程序不会以 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/

相关文章:

python - 将旋转的 xticklabel 与其各自的 xticks 对齐

python - 如何在散点自动放置的箭头上注释点

python - 将 python 文件夹添加到系统变量不起作用

Python 字典只返回 1 个条目?

python - 为什么在 ProcessPoolExecutor 中引发自定义异常时必须具有默认参数?

Java - 使用 For 循环创建多线程

android - 我应该使用什么?服务 ?异步任务?还有别的吗?

java - 方法同步,但由于非序列化线程行为,代码产生随机结果

C++ setTimeout函数?

c++ - 如何运行不阻塞我的主终端并允许多任务处理的 gtkmm 应用程序