Timeout a function in Python

Today, We will discuss how to timeout a function in Python.
Frequently, We need to run a function but when it takes too much time we want to terminate the function and want to continue our other task. This type of functionality can be achieved using thread.

Applying timeout function using thread in Python

If we want to implement timeout a function we need two threads-
1. The first thread is to execute the function.
2. The second thread is to measure the time taken by the function.
The only second thread should whether the time is over or not.
In this approach, we can not kill the thread in between because they hold some resources and memory spaces.
If we kill the thread forcefully then it causes some files and database connectivity remains unreleased.
Alternatively, we can use the event object from the threading module. Event object sends the signal from one thread to another thread

Example :

from threading import Thread, Event
import time
 
 
# It sends signals from one to another thread
bridge = Event()
 
 
def func():
    print('func() is started')
    """
    func will timeout after 3 seconds it will print a number starting from 1 and wait for 1 second 
    """
    x = 0
    while True:
        x += 1
        print(x)
        time.sleep(1)
 
        # Ensures whether the other thread sends the signals or not
        if bridge.is_set():
            break
 
 
if __name__ == '__main__':
    # Creating the main thread that executes the function
    main_thread= Thread(target=func)
 
    # We start the thread and will wait for 3 seconds then the code will continue to execute
    main_thread.start()
    main_thread.join(timeout=3)
 
    # sends the signal to stop other thread
    bridge.set()
 
    print("The function is timed out, you can continue performing your other task")

Output :

func() is started
1
2
3
The function is timed out, you can continue performing your other task

Note: To terminate the function it might take some time, we can not guarantee that it will take exactly 3 seconds to terminate.

Drawback: If we are using an external library in our program then it may be stuck in such code where we can not
access.

Also read:

Leave a Reply

Your email address will not be published. Required fields are marked *