【问题标题】:How to close a thread from within?如何从内部关闭线程?
【发布时间】:2011-05-31 06:47:57
【问题描述】:

对于每个连接到我的服务器的客户端,我都会生成一个新线程,如下所示:

# Create a new client
c = Client(self.server.accept(), globQueue[globQueueIndex], globQueueIndex, serverQueue )

# Start it
c.start()

# And thread it
self.threads.append(c)

现在,我知道我可以使用以下代码关闭所有线程:

    # Loop through all the threads and close (join) them
    for c in self.threads:
        c.join()

但是我怎样才能从那个线程inin关闭线程呢?

【问题讨论】:

  • .join() 不会关闭线程,它所做的一切都是等待(通过阻塞调用线程)让加入的线程自行终止。

标签: python multithreading


【解决方案1】:

当你启动一个线程时,它开始执行你给它的函数(如果你扩展threading.Thread,函数将是run())。要结束线程,只需从该函数返回即可。

根据this,也可以调用thread.exit(),会抛出异常,静默结束线程。

【讨论】:

  • thread.exit() 仅适用于线程对象,但不适用于 threading.Thread 类对象。
  • 看起来 exit() 方法在 python 3.7 中不可用调用后:threading.enumerate()[1].exit() 我收到一个错误:AttributeError: 'Thread' object has no attribute 'exit' 有什么替代方法吗?
【解决方案2】:

模块sys中的sys.exit()怎么样。

如果sys.exit() 在一个线程内执行,它只会关闭该线程。

这个答案在这里谈到:Why does sys.exit() not exit when called inside a thread in Python?

【讨论】:

  • 这是一个伟大而简单的解决方案。谢谢!此外,它可以与多处理模块或线程一起使用。
【解决方案3】:

有点晚了,但我使用_is_running 变量来告诉线程何时我想关闭。它很容易使用,只需在你的线程类中实现一个 stop() 即可。

def stop(self):
  self._is_running = False

而在run() 中只需循环while(self._is_running)

【讨论】:

    【解决方案4】:

    如果你想强制停止你的线程: thread._Thread_stop() 对我来说效果很好。

    【讨论】:

    • 为了改进您的答案,您应该在 when 它是比此处列出的其他选择更好的选择中加入,并附上指向一些支持它的文档的链接。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-06
    相关资源
    最近更新 更多