How to terminate a loop early in in a thread?

All we need is an easy explanation of the problem, so here it is.

I have a loop which makes a get request to a webservice to fetch data and do some stuff, but I want to ‘manually’ terminate the thread/event, which I achieved with the following example:

from threading import Event

exit = Event()

if external_condition():
    exit.set()

for _ in range(mins):
    fetch_data_and_do_stuff()
    exit.wait(10) #wait 10 seconds

With that, the only thing that terminates it’s the sleep time between loops. How can I also kill the loop so it doesn’t keep running until it gets to the last iteration?

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

nvm i’ve solved it like this

from threading import Event

exit = Event()

if external_condition():
    exit.set()

for _ in range(mins):
    fetch_data_and_do_stuff()
    if exit.wait(10):
         break

the condition returns true when killed and also sleeps the 10 seconds, so it works

Method 2

you have 2 options ,
kill the thread or process entirely
or making the loop’s boolean false. going that way
you could use a global variable in this way: [Python 3.7] , run it to see

from threading import Thread
from time import sleep

global glob
glob=True

def threaded_function():
    
    while glob:
        print("\n [Thread] this thread is running until main function halts this")
        sleep(0.8)


if __name__ == "__main__":
    thread = Thread(target = threaded_function, args = ())
    thread.start()

    for i in range(4,0,-1):
        print("\n [Main] thread will be terminated in "+str(i)+" seconds")
        sleep(1)
    
    glob=False
    
    while True:
        print("[Main] program is over")
        sleep(1)

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply