Home > OS >  How to terminate a loop early in in a thread?
How to terminate a loop early in in a thread?

Time:04-19

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?

CodePudding user response:

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

CodePudding user response:

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)
  • Related