當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。