Python Threads – acquire() Lock with timeout

In this Python Tutorial we will discuss the acquire() method for Locks. Or more specifically, we will be exploring an optional parameter called “timeout” in the acquire() method which can be used to control how long a Thread waits for a Lock.

Using timeout in acquire() Lock

By default, when we call the acquire() method on a lock object, this causes the thread to wait for the lock indefinitely (forever). We may not always want such behavior forever, so we have two options.

We can either use the blocking parameter to not wait at all, or we can use timeout parameter to specify a maximum duration for which a thread can remain blocked. Do not try to use blocking = False and timeout at the same time.

By default the value of timeout is -1 which means it will wait indefinitely.

It can also accept float values, not just integers!

Let’s take a look at a little example using timeout.

We have two threads, each calling a separate function. The first thread does “work” for 5 seconds. The second thread has a timeout for 3 seconds. What do you think the output will be?

from threading import Lock, Thread
from time import sleep

lock = Lock()

def func_2(lock):
    if lock.acquire(timeout = 3):
        print("Thread#2: Executed")
        print("Thread#2: Timeout")

def func_1(lock):
    print("Thread#1: Executed")

thread1 = Thread(target = func_1, args = (lock,))      
thread2 = Thread(target = func_2, args = (lock,))



The first thread, since it was created first got access to the lock and executed successfully. However, it took too long and the second thread’s acquire() function returned false as no lock was acquired.

Thread#1: Executed
Thread#2: Timeout

If we change the timeout amount to 10 seconds, the output will change to the following:

Thread#1: Executed
Thread#2: Executed

This marks the end of the Python Threads – acquire() Lock with timeout Tutorial. Any suggestions or contributions for CodersLegacy are more than welcome. Questions regarding the tutorial content can be asked in the comments section below.

Notify of
Inline Feedbacks
View all comments