Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to start and stop thread?

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
like image 548
user2229183 Avatar asked Mar 31 '13 12:03

user2229183


People also ask

How do you we start and stop the thread?

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.

How do you stop and start a thread in Python?

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.

How do you stop and start a thread in Java?

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.


1 Answers

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.

like image 175
David Heffernan Avatar answered Oct 13 '22 10:10

David Heffernan