Python Lock Class | acquire() Method with Example

Python Lock.acquire() Method: Here, we are going to learn about the acquire() method of Lock Class in Python with its definition, syntax, and examples.
Submitted by Hritika Rajput, on May 18, 2020

Python Lock.acquire() Method

acquire() is an inbuilt method of the Lock class of the threading module in Python.

This method is used to acquire a lock, either blocking or non-blocking. When it is invoked without arguments, it blocks the calling thread until the lock is unlocked by the thread using it currently.

Module:

    from threading import Lock 

Syntax:

    acquire( blocking=True, timeout=-1)

Parameter(s):

  • blocking: It is an optional parameter, which works as a blocking flag. If it is set to True, the calling thread will be blocked if some other thread is holding the flag and once that lock is released, then the calling thread will acquire the lock and return True. If it is set to False, it will not block the thread if the lock is already acquired by some other thread, and will return False. Its default value is True.
  • timeout: It is an optional parameter, which specifies the number of seconds for which the calling thread will be blocked if some other method is acquiring the lock currently. Its default value is -1 which indicates that the thread will be blocked for an indefinite time till it acquires the lock.

Note: It is forbidden to specify a timeout when blocking is false.

Return value:

The return type of this method is <class 'bool'>. The function is used to acquire a lock while implementing multithreading and returns True is lock was successfully acquired else returns False.

Example:

# Python program to show
# the use of acquire() method in Lock class
import threading
import random
                    
class shared(object):
  
    def __init__(self, x = 0):
        # Created a Lock object
        self.lock = threading.Lock()
        self.incr = x
        
        # Increment function for the thread
    def incrementcounter(self):
        print("Waiting for the lock to be unlocked")
        # Lock acquired by the current thread
        self.lock.acquire()
        try:
            print('Lock acquired, current counter value: ', self.incr)
            self.incr = self.incr + 1
        finally:
            print('Lock released, current counter value: ', self.incr)
            # Lock released by the given thread
            self.lock.release()

def helper_thread(c):
    # Getting a random integer between 1 to 3
    r = random.randint(1,3)
    print("Random value selected:", r)
    for i in range(r):
      c.incrementcounter()
    print('Finished', str(threading.current_thread().getName()))
    print()

if __name__ == '__main__':
    obj = shared()

    thread1 = threading.Thread(target=helper_thread, args=(obj,))
    thread1.start()
    
    thread2 = threading.Thread(target=helper_thread, args=(obj,))
    thread2.start()

    thread1.join()
    thread2.join()
    
    print('Final counter value:', obj.incr)

Output

Random value selected: 1
Waiting for the lock to be unlocked
Lock acquired, current counter value:  0
Lock released, current counter value:  1
Finished Thread-1

Random value selected: 2
Waiting for the lock to be unlocked
Lock acquired, current counter value:  1
Lock released, current counter value:  2
Waiting for the lock to be unlocked
Lock acquired, current counter value:  2
Lock released, current counter value:  3
Finished Thread-2

Final counter value: 3






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.