如何控制Python中的子线程进程?

2 投票
2 回答
1116 浏览
提问于 2025-04-15 20:26

代码先看:

'''this is main structure of my program'''

from twisted.web import http
from twisted.protocols import basic
import threading

threadstop = False    #thread trigger,to be done
class MyThread(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self.start()

    def run(self):
        while True:
            if threadstop:
                return
            dosomething()


'''def some function'''

if __name__ == '__main__':
    from twisted.internet import reactor
    t = MyThread()
    reactor.listenTCP(serverport,myHttpFactory())
    reactor.run()

这是我写的第一个多线程程序,能正常运行我很开心。不过现在我发现我无法控制它。如果我在前台运行,按下Control+C只能停止主进程,而子进程仍然在进程列表中;如果我在后台运行,就必须用 kill -9 pid 来强制停止它。我在想有没有办法通过一个触发变量来控制子线程,或者有没有比 kill -9 更好的方法来停止整个进程。

2 个回答

2

这不是直接回答你问题的内容,Alex已经回答了你的疑问,不过我有个想法想和你分享。

我注意到你在使用Python的threading模块。你有没有试过使用twisted.internet.threads呢?

当我在twisted应用中需要使用线程时,我通常会选择twisted.internet.threads

3

使用 atexit 模块,可以在主线程中注册一个函数,这个函数会把全局变量 threadstop 设置为 True。或者更简单的方法是,把线程对象的 daemon 属性设置为 True,这样如果主线程结束了,线程就不会再让整个程序继续运行。

撰写回答