8

How can I better write the following class? For example is there a nice way to slip having the 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) 

1 Answer 1

8

That's pretty much it. However, you don't need the 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 do need to find if a thread is running, you can call mythread.is_alive() - you don't need to set this yourself.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.