2

I was doing some reading(1,2,3) because I wanted to learn how to stop a thread properly.

I came up with a trivial example:

import time
import threading


def counting_numbers(stopper):
    for num in range(1,20):
        if not stopper.is_set():
            print(num)
            stopper.wait(2)


stop = threading.Event()
write = threading.Thread(target=counting_numbers, args=(stop,))
write.start()
time.sleep(5)
stop.set() 

Suppose if this was a GUI application and I had a cancel button, would the stop.set() go inside the cancel button handler allowing the user to hit cancel and stop the count?

  • Did you try it? did it work? – wwii Nov 16 '17 at 16:42
  • 1
    It did work, BUT just because it worked doesn't mean it's the proper practice or even the correct way of doing things –  Nov 16 '17 at 17:04
  • 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) Also see [How to stop a looping thread in Python?](https://stackoverflow.com/q/18018033/3904031) – uhoh Jul 31 '18 at 05:59

0 Answers0