在python中,在运行时只运行一次函数
需要将一些数据加载到内存中。为此,我需要确保执行此操作的函数在运行时只运行一次,无论调用多少次 我正在使用一个装饰程序以线程安全的方式完成这项工作。 以下是我使用的代码:在python中,在运行时只运行一次函数,python,python-3.x,Python,Python 3.x,需要将一些数据加载到内存中。为此,我需要确保执行此操作的函数在运行时只运行一次,无论调用多少次 我正在使用一个装饰程序以线程安全的方式完成这项工作。 以下是我使用的代码: import threading # Instantiating a lock object # This will be used to ensure that multiple parallel threads will not be able to run the same function at the same t
import threading
# Instantiating a lock object
# This will be used to ensure that multiple parallel threads will not be able to run the same function at the same time
# in the @run_once decorator written below
__lock = threading.Lock()
def run_once(f):
"""
Decorator to run a function only once.
:param f: function to be run only once during execution time despite the number of calls
:return: The original function with the params passed to it if it hasn't already been run before
"""
def wrapper(*args, **kwargs):
"""
The actual wrapper where the business logic to call the original function resides
:param args:
:param kwargs:
:return: The original function unless the wrapper has been run already
"""
if not wrapper.has_run:
with __lock:
if not wrapper.has_run:
wrapper.has_run = True
return f(*args, **kwargs)
wrapper.has_run = False
return wrapper
我是否需要在锁的外部和内部对
has_run
标志进行双重检查,以便不对过时的对象执行读取?您不能删除内部条件,因为一个线程可以通过外部条件,而另一个线程已经在锁定段内。您可以删除外部if条件,但这会导致第一个线程之后的每个线程都获得锁,然后立即返回,因为设置了标志,这可能会造成相当多不必要的开销/等待。“我想在这里检查两次国旗没问题。@Zinki我的想法完全正确。:)