Stop flow in python3

What is the best way to write the next class? For example, is there a good way to slip by having two flags is_alive and is_finished?

Monitor(threading.Thread): def run(self): resource = Resource("com1") self.alive = True self.is_finished = False try: while self.alive: pass # use resource finally: resource.close() self.is_finished = True def stop(self): self.alive = False while not self.is_finished: time.sleep(0.1) 
+7
source share
1 answer

This is pretty much the case. However, you do not need is_finished because you can use the join() method:

 Monitor(threading.Thread): def run(self): resource = Resource("com1") self.alive = True try: while self.alive: pass # use resource finally: resource.close() def stop(self): self.alive = False self.join() 

If you need to find if the thread is working, you can call mythread.is_alive() - you do not need to set this yourself.

+8
source

All Articles