views:

85

answers:

2

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 variale,or a better way to stop the whole process other than kill -9.Thanks.

+2  A: 

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.

Alex Martelli
+1 because Alex needs the rep...
msw
It works great,thank you!
SpawnCxy
@SpawnCxy, glad to hear this!
Alex Martelli
+2  A: 

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

jeffjose
As a newbie of python and twisted, i'm not familiar with this framework yet.And I'll check this class,thank you:)
SpawnCxy