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)
We can close a thread by returning from the run function at any time. This can be achieved by using the “return” statement in our target task function. If the threading. Thread class has been extended and the run() function overridden, then the “return” statement can be used in the run() function directly.
A thread automatically terminates when it returns from its entry-point routine. A thread can also explicitly terminate itself or terminate any other thread in the process, using a mechanism called cancelation.
You can suspend the calling thread for a given time in Python using the sleep method from the time module. It accepts the number of seconds for which you want to put the calling thread on suspension for.
Event can be checked via the is_set() function. The main thread, or another thread, can then set the event in order to stop the new thread from running. The event can be set or made True via the set() function. Now that we know how to stop a Python thread, let's look at some worked examples.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With