I'm currently in the process of writing some server code in python and I have a method which begins an infinite loop to serve requests ie:
class s:
def serve(self):
while True:
# do stuff
When I call this code I do something like:
a = s()
a.serve()
My question is -- is there way to send a message to 'serve' to disrupt the loop from outside the method. I don't want to simply kill the program. Help much appreciated.
One option I've thought of is rather than:
while True:
// do something
Could do:
while self.serving: # and then update self.serving as appropriate
But there's probably a better solution.
答案 0 :(得分:1)
Yes this is possible:
class Server:
def __init__():
self.alive = True
def serve(self):
while self.alive:
# do stuff
def die():
self.alive = False
Now just call die()
outside the thread running serve(..)
.
srv = Server()
thread = Thread(target=srv.serve)
thread.start()
time.sleep(some_time) # or do something else.
srv.die() # or do this from some outside process.
答案 1 :(得分:0)
I don't understand exactly what you're trying to do but could you have a simple flag rather than:
while True:
it could be
example = True
while example:
Then set example to false when you want to end the loop.