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


Python Lock locked()用法及代碼示例


Python Lock.locked() 方法

locked() 是 Python 中線程模塊的 Lock 類的內置方法。

如果鎖是由線程獲取的,則此方法返回 True,否則返回 False。

模塊:

    from threading import Lock

用法:

    locked()

參數:

  • None

返回值:

這個方法的返回類型是<class 'bool'>.它返回 True 是當前獲取的鎖,否則返回 False。

例:

# Python program to show
# the use of locked() 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()
        print("Is the lock acquired here:", self.lock.locked())
        try:
            print('Lock acquired, current counter value:', self.incr)
            self.incr = self.incr + 1
            print("Is the lock acquired here as well:", self.lock.locked())
        finally:
            print('Lock released, current counter value:', self.incr)
            # Lock released by the given thread
            self.lock.release()
            print("Is the lock acquired here after release:", self.lock.locked())

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)

輸出

Waiting for the lock to be unlocked
Is the lock acquired here:True
Lock acquired, current counter value: 0
Is the lock acquired here as well:True
Lock released, current counter value: 1
Is the lock acquired here after release:False
Finished Thread-1

Random value selected:3
Waiting for the lock to be unlocked
Is the lock acquired here:True
Lock acquired, current counter value: 1
Is the lock acquired here as well:True
Lock released, current counter value: 2
Is the lock acquired here after release:False
Waiting for the lock to be unlocked
Is the lock acquired here:True
Lock acquired, current counter value: 2
Is the lock acquired here as well:True
Lock released, current counter value: 3
Is the lock acquired here after release:False
Waiting for the lock to be unlocked
Is the lock acquired here:True
Lock acquired, current counter value: 3
Is the lock acquired here as well:True
Lock released, current counter value: 4
Is the lock acquired here after release:False
Finished Thread-2

Final counter value:4


相關用法


注:本文由純淨天空篩選整理自 Python Lock Class | locked() Method with Example。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。