Free cookie consent management tool by TermsFeed The release() method of lock class in Python | Pythontic.com

The release() method of lock class in Python

Overview:

  • A call to the release() function makes the state of the Lock object into unlocked state.

  • When a Lock object is in unlocked state, a subsequent call to the acquire() succeeds and the block enclosed within the acquire() and release() calls is entered by the thread. Calling the acquire() method makes the lock object into unlocked state.

  • If a thread owning the lock does not call release(), the other threads who invoked acquire() and waiting for their turn to acquire the lock will not succeed. This could lead to starvation and dead-lock scenarios (Owning thread is the one which most recently called the acquire() method and started executing the next statement after the acquire()). In Python, threads are created using the Thread class.

  • The acquire() call can be made through the with statement which ensures release() is called even in case of any exception after the acquire() call is made.

Example:

# Example Python program that serializes access to 
# a crtitical resource by using a Lock object and
# calling the acquire() and release() methods 

import threading as th
import time
import sys

# The counter
err_num = 0

# Reader thread
def read(updateEvent, terminate):
    while(terminate.wait(5.0)):
        if(updateEvent.wait(5.0)):
            time.sleep(0.01)
            print("Count value:%d"%err_num)

# Thread function for the increment threads
def incr(lock, updateEvent, thread_num):
    global err_num

    # Synchronized access to the counter
    with lock:
        time.sleep(.01)
        err_num += 1

    updateEvent.set()
    print("Thread %d exiting"%thread_num)

# Print Global Interpreter Lock(GIL) is status
print("GIL status:")
print(sys._is_gil_enabled())

# Create a lock
l = th.Lock()
threads = []

# Create events
countUpdate = th.Event()
countUpdate.clear()

threadsAlive = th.Event()
threadsAlive.clear()

# Create a reader thread
r = th.Thread(target = read, args = (countUpdate, threadsAlive))
r.start()

# Spawn writer threads
for i in range(0, 10):
    if i == 1:
        threadsAlive.set()
        print("At least one thread alive")
    t = th.Thread(target     = incr, 
                  args         = (l, countUpdate, i),)

    t.start()
    threads.append(t)

# Wait for the threads to complete
for t in threads:
    t.join()
countUpdate.clear()
threadsAlive.clear()
r.join()

# Print the final value of the counter
print("Final count:%d"%err_num)

Output:

GIL status:
False
At least one thread alive
Thread 0 exiting
Thread 1 exiting
Count value:2
Thread 2 exiting
Count value:3
Count value:4
Thread 3 exiting
Count value:5
Thread 4 exiting
Count value:5
Thread 5 exiting
Count value:7
Thread 6 exiting
Count value:7
Thread 7 exiting
Count value:8
Thread 8 exiting
Thread 9 exiting
Count value:10
Final count:10

 


Copyright 2025 © pythontic.com