开发者

How to control a subthread process in python?

Code first:

'''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()

As my first multithread program,I feel happy that it works as expected. But now I find I cannot control it. If I run it on front,Control+C can only stop the main process, and I can still find it in processlist; if 开发者_高级运维I run it in background,I have to use kill -9 pid to stop it. And I wonder if there's a way to control the subthread process by a trigger variable, or a better way to stop the whole process other than kill -9.


Use the atexit module to register (in the main thread) a function that set the global threadstop to True, or, more simply, set the daemon attribute of the thread object to True so it won't keep the process alive if the main thread exits.


This is not a direct answer to your question and Alex has already addressed your query, but here's a thought.

I see you're using python's threading. Did you try using twisted.internet.threads ?

When I find myself using threads in a twisted application, I go to twisted.internet.threads

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜