Python 如何从内部关闭线程?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4541190/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 16:14:24  来源:igfitidea点击:

How to close a thread from within?

pythonmultithreading

提问by skerit

For every client connecting to my server I spawn a new thread, like this:

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

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

# Start it
c.start()

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

Now, I know I can close allthe threads using this code:

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

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

But how can I close the thread from withinthat thread?

但是,如何从关闭线程该线程?

采纳答案by Brendan Long

When you start a thread, it begins executing a function you give it (if you're extending threading.Thread, the function will be run()). To end the thread, just return from that function.

当您启动一个线程时,它会开始执行您提供给它的函数(如果您要扩展threading.Thread,则该函数将为run())。要结束线程,只需从该函数返回。

According to this, you can also call thread.exit(), which will throw an exception that will end the thread silently.

根据这个,你也可以打电话thread.exit(),这将抛出一个异常,将安静地结束线程。

回答by Eric Fossum

A little late, but I use a _is_runningvariable to tell the thread when I want to close. It's easy to use, just implement a stop() inside your thread class.

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

def stop(self):
  self._is_running = False

And in run()just loop on while(self._is_running)

并且在run()循环中while(self._is_running)

回答by iFA88

If you want force stop your thread: thread._Thread_stop()For me works very good.

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

回答by kryptokinght

How about sys.exit()from the module sys.

sys.exit()从模块怎么样sys

If sys.exit()is executed from within a thread it will close that thread only.

如果sys.exit()从线程内执行,它将仅关闭该线程。

This answer here talks about that: Why does sys.exit() not exit when called inside a thread in Python?

这个答案在这里谈到:为什么 sys.exit() 在 Python 中的线程内部调用时不退出?