我有一个多线程使用的函数。由于其性质,此功能应该一次只调用一次。多个线程同时调用该函数可能不好。
如果某个线程正在使用该函数,则其他线程必须等待它自由。
我的背景不是编码,所以我不确定,但我相信这在术语中被称为“锁定”?我尝试了谷歌搜索,但没有找到Python3的简单示例。
简化案例:
def critical_function():
# How do I "lock" this function?
print('critical operation that should only be run once at a time')
def threaded_function():
while True:
# doing stuff and then
critical_function()
for i in range(0, 10):
threading.Thread(target=threaded_function).start()
答案 0 :(得分:2)
from threading import Lock
critical_function_lock = Lock()
def critical_function():
with critical_function_lock:
# How do I "lock" this function?
print('critical operation that should only be run once at a time')