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


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


Python Lock.release() 方法

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

此方法释放线程先前获取的锁。一旦锁被释放,它就可以被另一个线程获取。这可以从任何线程调用,而不仅仅是从获取它的线程调用。释放未锁定的锁时,会引发 RuntimeError。

模块:

    from threading import Lock

用法:

    release()

参数:

  • None

返回值:

这个方法的返回类型是<class 'NoneType'>.它释放获得它的线程。

例:

# Python program to show
# the use of release() 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:2
Waiting for the lock to be unlocked
Lock acquired, current counter value: 0
Lock released, current counter value: 1
Waiting for the lock to be unlocked
Lock acquired, current counter value: 1
Lock released, current counter value: 2
Finished Thread-1

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

Final counter value:5


相关用法


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