Is it possible to send a break/stop signal to a method?

时间:2017-04-10 00:27:17

标签: python oop

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.

2 个答案:

答案 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.