如何从内部关闭线程? [英] How to close a thread from within?

查看:267
本文介绍了如何从内部关闭线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 all the 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 within that thread?

推荐答案

启动线程时,线程开始执行您赋予它的函数(如果要扩展threading.Thread,则该函数将为run()).要结束线程,只需从该函数返回即可.

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.

根据,您还可以调用thread.exit(),它将抛出一个异常,该异常将使线程静默结束.

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

这篇关于如何从内部关闭线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆