0

I'm trying to use a button to stop all threads I've created in the for loop. Is there a method to stop threads?

Here's my code:

import threading
import time
from tkinter import *

tk= Tk()

class go(threading.Thread):

    def __init__(self,c):
        threading.Thread.__init__(self)
        self.c = c
    def run(self):
        while 1 == 1 :
            time.sleep(5)
            print('This is thread: '+str(self.c))


for count in range(10):
    thread = go(count)
    thread.start()

btn1 = Button(tk, text="Stop All", width=16, height=5)
btn1.grid(row=2,column=0)

tk.mainloop()
coderoftheday
  • 1,987
  • 4
  • 7
  • 21
  • No, you can't stop them. See [my answer](https://stackoverflow.com/a/15734837/355230) to a related question. – martineau Sep 04 '20 at 18:42

1 Answers1

0

You need to provide a condition to quit the while loop in the run() method. Normally threading.Event object is used:

def __init__(self, c):
    ...
    self.stopped = threading.Event()

Then you need to check whether the Event object is set using Event.is_set():

def run(self):
    while not self.stopped.is_set():
        ...

So to terminate the thread, just set the Event object. You can create a class method to do it:

def terminate(self):
    self.stopped.set()

Below is a modified example based on yours:

import threading
import time
from tkinter import *

tk = Tk()

class go(threading.Thread):
    def __init__(self,c):
        threading.Thread.__init__(self)
        self.c = c
        self.stopped = threading.Event()

    def run(self):
        while not self.stopped.is_set():
            time.sleep(5)
            print(f'This is thread: {self.c}')
        print(f'thread {self.c} done')

    def terminate(self):
        self.stopped.set()


threads = []  # save the created threads
for count in range(10):
    thread = go(count)
    thread.start()
    threads.append(thread)

def stop_all():
    for thread in threads:
        thread.terminate()

btn1 = Button(tk, text="Stop All", width=16, height=5, command=stop_all)
btn1.grid(row=2, column=0)

tk.mainloop()
acw1668
  • 40,144
  • 5
  • 22
  • 34