Home > other >  Actual Timeout in Python
Actual Timeout in Python

Time:09-13

I am trying to add a timeout function,

def doit(stop_event, arg):
    while not stop_event.is_set(): #currently, to stop the thread, Event needs to be checked in the while condition
        <calculation part> # if the calculation part takes more time, then the thread needs to be stopped
        print ("working on %s" % arg)
    print("Stopping as you wish.")


def main():
    pill2kill = threading.Event()
    t = threading.Thread(target=doit, args=(pill2kill, "task"))
    t.start()
    time.sleep(5)
    pill2kill.set()
    t.join()

In this code, the timeout works using the Event, but it needs to be checked whether, the event is set or not in while loop.

But, How to stop the thread - if the <calculation part> takes more time[more than 5 seconds], then at that time also the thread needs to be stopped [the thread should not wait until the completion of <calculation part> and then check for the Event to decide to stop the thread]

is there is a way to do that using Thread in python?, I go through most of the blogs, all of the methods are using the loop concept to check to stop/continue the thread, is there any way to do without for/while loop?

Thanks

CodePudding user response:

Documentation for Python's standard threading module says,

...threads cannot be destroyed, stopped, suspended, resumed, or interrupted.

There's good reason for that. Threads communicate by mutating shared program state. If there is any place in your program that needs a mutex—any place at all, whether it's in code that you wrote, or in some library that your code calls, or in the language interpreter itself*—then that's because it's possible for one thread to temporarily put the shared variables into some illegal/invalid/broken state that other threads should not be allowed to see.

If one thread can kill another at any time, then there's no way to guarantee that the kill won't leave the shared variables in that illegal/invalid/broken state, and cause the program to malfunction or crash.


How to stop the thread - if the <calculation part> takes more time...?

The best option would be if you can modify the <calculation part> so that it periodically checks the stop_event during the calculation. If it sees the flag set, then it should abort the calculation and clean up whatever needs to be cleaned up before it returns.


* E.g., Python's notorious GIL. If Python needs the GIL, then it's a sure thing that it's never safe to kill a Python thread.

  • Related