How to use Python Lock in a “with” statement

In this tutorial we will discuss how to create and handle a Python Lock using the “with” statement.


Introduction

Normally when we want to use Thread Locks in Python, we use the following format.

lock.acquire()
# Perform some operation here
sleep(1)
lock.release()

We need to make two calls here to acquire() and release(), in between which we write the critical section code.

There is actually an easier method of handling a Lock by using the “with” statement in Python.

with lock:
    # Perform some operation here
    sleep(1)

It does look rather unbelievable, but the “with” statement is designed for resource management, and automates the acquisition and releasing of resources. It is also commonly used in File handling for opening and closing file streams.


Using Locks with Python “with” statement

Let’s take a look at an actual code example now.

The below code features two threads which attempt to enter their critical sections. You will notice that the rules of mutual exclusion are being obeyed here thanks to the Lock inside the “with” statement.

from threading import Thread, Lock
from time import sleep
import sys

print = lambda x: sys.stdout.write("%s\n" % x)
lock = Lock()

def func(lock, id):
    print(f"Thread {id}: Waiting for Lock")

    with lock:
        print(f"Thread {id}: Acquired the Lock")
        sleep(1)

    print(f"Thread {id}: Released Lock")


thread1 = Thread(target=func, args=(lock, 1))
thread2 = Thread(target=func, args=(lock, 2))

thread1.start()
thread2.start()

thread1.join()
thread2.join()
Thread 1: Waiting for Lock
Thread 1: Acquired the Lock
Thread 2: Waiting for Lock
Thread 1: Released Lock
Thread 2: Acquired the Lock
Thread 2: Released Lock

To help cement your concepts, you should replace the “with” statement with the regular acquire() and release() functions. You can then confirm that the output of both codes are the same!


This marks the end of the How to create a non blocking Thread in Python Tutorial. Any suggestions or contributions for CodersLegacy are more than welcome. Questions regarding the tutorial content can be asked in the comments section below.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments