【问题标题】:How to control a subthread process in python?如何在python中控制子线程进程?
【发布时间】:2010-03-15 01:48:31
【问题描述】:

代码优先:

'''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只能停止主进程,在processlist中还是可以找到的;如果我在后台运行它,我必须使用kill -9 pid 来停止它。而且我想知道除了kill -9之外,有没有办法通过触发变量来控制子线程进程,或者有更好的方法来停止整个进程。

【问题讨论】:

    标签: python multithreading twisted


    【解决方案1】:

    使用atexit模块注册(在主线程中)一个将全局threadstop设置为True的函数,或者更简单地,将线程对象的daemon属性设置为True所以如果主线程退出,它不会让进程保持活动状态。

    【讨论】:

    • @SpawnCxy,很高兴听到这个消息!
    【解决方案2】:

    这不是您问题的直接答案,Alex 已经解决了您的问题,但这里有一个想法。

    我看到你正在使用 python 的threading。你试过使用twisted.internet.threads 吗?

    当我发现自己在 twisted 应用程序中使用线程时,我会转到 twisted.internet.threads

    【讨论】:

    • 作为python和twisted的新手,我对这个框架还不熟悉。我会检查这个类,谢谢:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-28
    • 1970-01-01
    • 2021-07-12
    • 2018-07-19
    • 2021-09-05
    • 2019-02-14
    • 2011-10-17
    相关资源
    最近更新 更多