1

My code runs N number of threads. I want to stop specific threads on some condition but the remaining threads should continue running. I am doing some operation once each thread finishes its job. Is there a way to stop running thread in Python 3.

My current code is implemented in Python2 which does this by "_Thread__stop()". Is there any identical thing in Python3?

Vinaykumar Patel
  • 864
  • 11
  • 26
  • 4
    You realize [there is *no* safe way to kill a thread](https://stackoverflow.com/q/323972/364696), even when some misguided APIs (like WinAPI) allow it, right? Among the most basic issues, if it holds a lock (not just one of your locks, it could be some implicit lock in a library or allocator you never see), that lock is held forever, and any other thread that needs it is blocked, forever. – ShadowRanger Nov 01 '19 at 11:44

2 Answers2

0

The practice is to "signal" the thread that it is time to finish and then the thread needs to exit. This is not killing like you kill a process but a regular state machine behavior of your thread function.

For example, suppose your thread is lopping. You should insert an if statement inside the loop that instructing the thread function to break or return if stop is True. The stop variable should be a shared variable with the main thread (or the thread who need to stop out thread) that will change it to True. usually after this, the stopper thread will want to wait for the thread completion by join()

Lior Cohen
  • 5,570
  • 2
  • 14
  • 30
0

It's a bad habit to kill a thread, better is to create a "flag" which will tell you when your thread made its work done. Consider the following example:

import threading
import random

class CheckSomething(threading.Thread):
    def __init__(self, variable):
        super(CheckSomething, self).__init__()
        self.start_flag = threading.Event()
        self.variable = variable

    def check_position(self, variable):
        x = random.randint(100)
        if variable == x:
            self.stop_checking()

    def run(self):
        while True:
            self.check_position(self.variable) 

    def stop_checking():
        self.start_flag.set()

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

The set() method of Event() set its status to True. More you can read in docs: https://docs.python.org/3.5/library/threading.html

So you need to call stop_checking() when you meet a condition where you want exit.