×

Python lock

Before understanding the concept of Python-lock we need to understand what kind if condition we require to implement the locks in Python. Let us start with multithreading and its implementation in python.

Multithreading in Python

Threads can be defined as lightweight processes that run in a certain order in order to perform a certain task. Nowadays, when computers have multiple processors it has enabled the user to run multiple threads at the same time to perform several tasks parallelly. This process of executing multiple threads at the same time is what we call multithreading.

Threading in Python

Python has a threading module, using this module we can easily implement multithreading in our program. This module enables the user not only to create threads but we can also to control and manage those threads in python.

Implementation of Threading

To implement threading in the program, the Thread module provides certain classes whose object performs specific functioning while executing these threads.

Some of the important objects in the threading module are:

ObjectsDescription
ThreadIt represents the execution of a single thread.
LockIt is the primitive lock with only two states that is Lock and Unlock. Once unlocked it cannot be reversed.
RLockIt allows recursive locking which means we can acquire a released lock again.
ConditionIt is the phase where a lock awaits while a certain lock awaits for the other lock to perform its task.
EventIt involves several locks waiting for a particular event to happen.
SemaphoreAn internal counter for the shared resources
TimerThis represents the execution of the thread, along with a time constraint for which the thread requires to wait before execution.
BarrierThis object stops the threads at a point until a required number of threads reach that point.

Race Condition

While performing multiple threading it might be possible that multiple threads try to access and modify the same resource. If all the locks are allowed to modify the resource at the same time it would produce erroneous results. This condition where multiple threads modify the shared resource concurrently is called the Race Condition. It is necessary to prevent this to prevent the data from getting corrupted.

To avoid this situation, we need to synchronize the access and modification of the resources by various threads. This is done by using locks in python.

Primitive Lock Object

Any lock in python can either be:

  1. Locked
  2. Unlocked

For locking the lock, we use acquire() method. Once the thread is in this stage, it cannot be acquired by any other thread and the resource is limited to the particular thread until the lock is released.

To release a lock, we need to use the release() method. When we use this method on any locked lock it automatically changes its state into unlocked. If we use this method on an already unlocked lock, then it will throw an error.

acquire() method: This method is used to acquire the lock on the thread, using this method we can lock the thread until we wish to free the thread or we can pass two optional parameters specifying when to unlock the lock.

acquire(blocking=True, Timeout=-1) method: Two arguments can be passed in this method.

  1. blocking: if this argument is passed as False, it will not block the thread even when the lock is being acquired by any other thread, it will only be blocked if this flag is passed as True. Once set True it will acquire the lock and return True as the value otherwise it would not acquire the lock and return False as the value.
  2. Timeout: this argument holds the number of seconds till which you want the thread to be locked. The default value to this parameter is -1, this specifies that the lock is to be acquired for a definite time. We need to pass positive floating-point values to this parameter.

release() method: This method is used to free the lock, if the lock is locked, and the thread has been executed we release the lock with the help of using this method; so that it can be accessed by other threads in the program. It resets the lock to unlock. If this method is invoked on an already unlocked lock, this will throw a Runtime error.

RLock Objects

RLock stands for Re-entrant Lock. The problem that arise by using primitive lock was that we were not able to re-lock the thread. That means we cannot use the acquire() method on a lock twice. To solve this problem, we use RLock. The primitive lock only performs the locking without recognising that which is the thread holding the lock. It prevents unnecessary blocking from accessing the shared resources. If we have a resource that is locked using re-entrant lock, the resource can be called and accessed again without getting blocked. But unlike the primitive lock, this lock can only be released by the thread that is currently using this lock. It makes the accessing of shared resources easier and safer.

Now, let’s implement what we have learned:

import threading
import time
from random import randint


class SCnt(object):

    def __init__(self, value=0):
        self.lock = threading.Lock()
        self.counter = value

    def increment(self):
        print("Wait while the lock is being acquired")
        self.lock.acquire()
        try:
            print('lock is acquired, counter value: ', self.counter)
            self.counter = self.counter + 1
        finally:
            print('lock is freed, counter value: ', self.counter)
            self.lock.release()


def task(c):
    # Choose a random number
    random_no = randint(1, 5)
    # performing  increment on the random numbers
    for i in range(random_no):
        c.increment()
    print('Done')


if __name__ == '__main__':
    sCounter = SCnt()

    task1 = threading.Thread(target=task, args=(sCounter,))
    task1.start()

    task2 = threading.Thread(target=task, args=(sCounter,))
    task2.start()

    print('Wait for the worker threads to get loaded')
    task1.join()
    task2.join()

    print('Counter:', sCounter.counter)

In this Program, we have created a class SCnt that is being shared among various threads. The task method we have called the increment() function will access the same counter and will increment the value of the counter. The value of the counter is inconsistent due to the concurrent modifications that are being performed on it.


Related Topics

Python Lists vs Tuples

The difference between lists and tuples is one of the most frequently asked questions in an interview related to python language. Lists and Tuples are two of Python’s built-in data...

4 minutes read.

Python program to add two number

Python program to add two number This program will add the two numbers and display their sum on the screen. Example: Input: Number1 = 20        Number2 = 30   Output: Sum =...

2 minutes read.

Python Set union() method

Python Set union() method The set.union() method in Python returns a set that contains all items from the original set and all items from the specified sets. Syntax set.union(set1, set2...) Parameter set1- This parameter represents the first set...

2 minutes read.

Data Structures and Algorithms Using Python | Part 1

Data Structures: Data Structure is defined as a way to organize and store the data so that we can access the data and work more efficiently. Data structures also describe the...

18 minutes read.

Python vs PHP

Python Python is a high-level, object-oriented, interpreted language that is used to create independent program and algorithms for a variety of applications. It has a large library support base. In 1990,...

3 minutes read.

Event Key in Python

Python Programming Language: Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It...

3 minutes read.

Python Project Ideas for Advanced Developers

Best Python Project Ideas for Advanced Developers Python is an object-oriented, high-level, interpreted programming language created by a developer known Guido Van Rossum. Python is one of the languages that gathered...

9 minutes read.

Python whois

What is whois? Whois is a protocol used to identify the owner of the registered domain name. It is a querying database that is used to record the registered users. WHOIS is...

4 minutes read.

How to reverse a string in python

How to reverse a string in python A Brief About Strings- The String is a data type in Python that has a sequence of characters. This series of characters are represented in...

4 minutes read.

Python Namespace

In python, the namespace is a very important concept that should be understood before using any function or variables. When we write code, we often use variables, libraries, functions, modules, etc....

4 minutes read.

Check Letter in a String Python

Checking a specific letter or a character in a given string or a string which is taken as an input from the user is possible in Python in broadly three...

3 minutes read.

List in Python

What is List in Python In Python, lists are used to store the multiple values in one variable. We can say that list is the collection of similar as well as...

3 minutes read.

How to import numy in python

How to Install NumPy in Python Python is a vast ocean of libraries, modules, and different functions. It has a solution for almost everything. Using Python, we can simplify even a...

3 minutes read.

Dictionary to JSON Python

In python JSON (JavascriptObject Notation). In the programming language, the text file is made using the script file.We can use many built-in packages which arenamedJSON.Before using the packages, we have...

3 minutes read.

Python MySQL Delete Operation

Python MySQL Delete Operation: Like the update operation where we were updating required field from a SQL table, we can also delete an entry from the table which we have...

4 minutes read.

Python Random Module

The tutorial for the Python random module demonstrates how to produce pseudo-random integers in Python. Random Number Generator (RNG) The RNG (random number generator) generates a series of values with no discernible...

8 minutes read.

Abstraction in Python

What is meant by abstraction generally? A very general notion of a thing or work is known as abstract. To be more precise, the process of having a brief idea but...

4 minutes read.

Python Set isdisjoint() method

Python Set isdisjoint() method The set.isdisjoint() method in Python returns a boolean value True if two sets are disjoint sets ( i.e. none of the elements are present in both sets), otherwise it returns...

1 minute read.

Python Struct

Python Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

3 minutes read.

How to run a Python file in CMD

Introduction Today, let us learn about how to run a Python file using cmd. Cmd is nothing but command prompt. So first let us know how to run a Python code...

4 minutes read.