【问题标题】:Python threading - blocking operation - terminate executionPython线程 - 阻塞操作 - 终止执行
【发布时间】:2015-09-18 19:07:06
【问题描述】:

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

现在,我可以简单地将blocking_function() 的执行超时,但这并不好玩。我可以在KeyboardInterrupt 或类似的网站上取消阻止它吗?

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

【问题讨论】:

    标签: python multithreading


    【解决方案1】:

    也许有一点解决方法,但您可以使用thread 而不是threading。不建议这样做,但如果它适合您和您的程序,为什么不这样做。

    您需要保持程序运行,否则线程在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)
    

    【讨论】:

    • 它现在确实以 Ctrl+C 终止。但是为什么thread 不这样做而不是threading??
    猜你喜欢
    • 2013-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-24
    • 2019-09-02
    相关资源
    最近更新 更多