Sorry for the old question. I have clarified it. How can I start an stop thread with my poor thread class?
EDIT: It is in loop, I want to restart it again at the beginning of the code. How can I do start-stop-restart-stop-restart?
My class:
import threading
class Concur(threading.Thread):
def __init__(self):
self.stopped = False
threading.Thread.__init__(self)
def run(self):
i = 0
while not self.stopped:
time.sleep(1)
i = i + 1
In the main code, I want:
inst = Concur()
while conditon:
inst.start()
#after some operation
inst.stop()
#some other operation
Modern ways to suspend/stop a thread are by using a boolean flag and Thread. interrupt() method. Using a boolean flag: We can define a boolean variable which is used for stopping/killing threads say 'exit'. Whenever we want to stop a thread, the 'exit' variable will be set to true.
You can't actually stop and then restart a thread since you can't call its start() method again after its run() method has terminated. However you can make one pause and then later resume its execution by using a threading. Condition variable to avoid concurrency problems when checking or changing its running state.
start(); To stop a Thread: thread. join();//it will kill you thread //if you want to know whether your thread is alive or dead you can use System. out. println("Thread is "+thread.
The implementation of stop()
would look like this:
def stop(self):
self.stopped = True
If you want to restart, then you can just create a new instance and start that.
while conditon:
inst = Concur()
inst.start()
#after some operation
inst.stop()
#some other operation
The documentation for Thread
makes it clear that the start()
method can only be called once for each instance of the class.
If you want to pause and resume a thread, then you'll need to use a condition variable.
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