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 import threading as th # The counter # Reader thread # Thread function for the increment threads # Synchronized access to the counter updateEvent.set() # Print Global Interpreter Lock(GIL) is status # Create a lock # Create events threadsAlive = th.Event() # Create a reader thread # Spawn writer threads t.start() # Wait for the threads to complete # Print the final value of the counter |
Output:
GIL status: |