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
threadstoptoTrue, or, more simply, set the daemon attribute of the thread object toTrueso it won’t keep the process alive if the main thread exits.