H
H
Hector Synchrome2021-07-02 10:34:52
Python
Hector Synchrome, 2021-07-02 10:34:52

How to stop a Thread?

The function invokes a thread (a progress bar for that function). How can I stop the thread when this function completes.

def main_func():
    thread_indicator = threading.Thread(target=indicator_edit)
    thread_indicator.start()
    time.sleep(5) # do something
    # thread.kill()

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Shitskov, 2021-07-02
@Zarom

There is no native solution to this problem. Found this handy example .

class StoppableThread(threading.Thread):
    """Thread class with a stop() method. The thread itself has to check
    regularly for the stopped() condition."""

    def __init__(self,  *args, **kwargs):
        super(StoppableThread, self).__init__(*args, **kwargs)
        self._stop_event = threading.Event()

    def stop(self):
        self._stop_event.set()

    def stopped(self):
        return self._stop_event.is_set()

Then your thread will have a stop() method that can be called. But the function itself, running in this thread, should regularly check the value of stopped() and exit as soon as the value becomes True.
The caller of stop() must execute join() to ensure that the Thread has definitely completed its execution.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question