当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Python Lock acquire()用法及代码示例


Python Lock.acquire() 方法

acquire() 是 Python 中线程模块的 Lock 类的内置方法。

此方法用于获取锁,阻塞或非阻塞。当它在没有参数的情况下被调用时,它会阻塞调用线程,直到当前使用它的线程解锁锁。

模块:

    from threading import Lock 

用法:

    acquire( blocking=True, timeout=-1)

参数:

  • blocking:它是一个可选参数,用作阻塞标志。如果设置为 True,调用线程将在其他线程持有该标志时被阻塞,一旦该锁被释放,调用线程将获取该锁并返回 True。如果设置为 False,则如果其他线程已获取锁,则不会阻塞该线程,并返回 False。其默认值为 True。
  • timeout:它是一个可选参数,它指定如果其他方法当前正在获取锁,调用线程将被阻塞的秒数。它的默认值是 -1,表示线程将被无限期阻塞,直到它获得锁。

注意:blocking 为 false 时禁止指定超时。

返回值:

这个方法的返回类型是<class 'bool'>.该函数用于在实现多线程时获取锁,如果成功获取锁则返回 True,否则返回 False。

例:

# 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)

输出

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


相关用法


注:本文由纯净天空筛选整理自 Python Lock Class | acquire() Method with Example。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。