在python中运行时只运行一次函数

时间:2018-06-18 06:56:58

标签: 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 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标志进行一次双重检查,以便在陈旧对象上进行读取?

0 个答案:

没有答案