0

I'm running an async program, and every thread I start, I would like it

to have a timeout, that if it didn't complete the function it will just stop and kill itself(or some other thread will kill it)

func(my_item, num1, num2, num3, timeout):
    calc = num1+num2
    # something that takes long time(on my_item)

for item in my_list:
        if item.bool:
            new_thread = threading.Thread(target=func, (item, 1, 2, 3, item.timeout))
            new_thread.start()

Now I want the main thread to keep on starting new threads, but I also want every thread to have a timeout to it, so that thread won't go on forever.

I'm using windows not UNIX, so I can't run SINGLRM

Thank You!

miltone
  • 4,416
  • 11
  • 42
  • 76
Mumfordwiz
  • 1,483
  • 4
  • 19
  • 31

1 Answers1

1

Killing threads is a bad practice, it is better for the long running function to check a state flag and exit itself, as opposed to an external factor killing the thread abruptly. A simple check that recorded the start time of the function call with time.time() and compare that at intervals, ie:

def func(x, y, timeout):
    start = time.time()
    while time.time() < (start + timeout):
        # Do stuff

or add a method that the function can call at intervals that will raise an Exception when the timeout is exceeded that your long running function can catch in try/except block to clean up and exit the thread:

def check_timeout(start_time, timeout):
    if time.time() > (start_time + timeout):
        raise TimeoutException

try:
    # Stuff
    check_timeout(start_time, timeout)
    # Bit more stuff
    check_timeout(start_time, timeout)
    # Bit more stuff
    check_timeout(start_time, timeout)
    # Bit more stuff
    # All done!
    return "everything is awesome"

except TimeoutException:
    # Cleanup and let thread end

I would recommend this thread as a good read: Is there any way to kill a Thread in Python?

Community
  • 1
  • 1
J2C
  • 497
  • 4
  • 8