python 示例
Python Lock.release()方法 (Python Lock.release() Method)
release() is an inbuilt method of the Lock class of the threading module in Python.
release()是Python中线程模块的Lock类的内置方法。
This method releases the lock which was earlier acquired by a thread. Once the lock is released, only then can it be acquired by another thread. This can be called from any thread, not just from the thread that acquired it. When an unlocked lock is released, a RuntimeError is raised.
此方法释放线程先前获取的锁。 一旦释放锁,则只有另一个线程才能获取它。 可以从任何线程中调用它,而不仅仅是从获取它的线程中调用。 释放解锁的锁后,将引发RuntimeError 。
Module:
模块:
from threading import Lock
Syntax:
句法:
release()
Parameter(s):
参数:
None
没有
Return value:
返回值:
The return type of this method is <class 'NoneType'>. It releases the thread which had acquired it.
此方法的返回类型为<class'NoneType'> 。 它释放获取它的线程。
Example:
例:
# 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)
Output
输出量
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
翻译自: https://www.includehelp.com/python/lock-release-method-with-example.aspx
python 示例