0

I'm looking for this question online but I can not find any way to do it directly I'm trying the following

class Test(Thread):
    def __init__(self):
        Thread.__init__(self)

    def run(self):
        for i in range(3):
            time.sleep(1)
            print(i)


def main():
    test = Test()
    test.start()
    del test
    time.sleep(5)
    print('end')

main()

the only way to stop the thread is from the run method when the code ends but I can not find any way to end the thread.

whackamadoodle3000
  • 6,684
  • 4
  • 27
  • 44
Francisco
  • 539
  • 2
  • 8
  • 25
  • 2
    Possible duplicate of [Is there any way to kill a Thread in Python?](https://stackoverflow.com/questions/323972/is-there-any-way-to-kill-a-thread-in-python) – MoxieBall Jun 26 '18 at 20:42

2 Answers2

1

You can't. All you can do is ask it nicely (by implementing some sort of inter thread communication like a threading.Queue object, then making your thread check it for instructions) and hope for the best.

nosklo
  • 217,122
  • 57
  • 293
  • 297
0

You can use this simple approach to stop/kill/end a child thread from the parent thread using some variable that is being checked in child thread periodically:

from threading import Thread
from time import time, sleep


class Test:
    some_var = True

    def __init__(self):
        self.t = Thread(target=self.worker)
        #self.t.setDaemon(True)
        self.t.start()

    def worker(self):
        while self.some_var is True:
            print("%s > I'm running" % str(time()))


test = Test()
sleep(2)
test.some_var = False
print("End!")

Let me know if I didn't understand your question, but I think I've answered your question "How to end with a thread from the main thread?".

Artsiom Praneuski
  • 2,259
  • 16
  • 24