Skip to content

Commit

Permalink
dev(narugo): add docs for this function
Browse files Browse the repository at this point in the history
  • Loading branch information
narugo1992 committed Nov 7, 2024
1 parent 318820f commit 756c977
Show file tree
Hide file tree
Showing 3 changed files with 58 additions and 0 deletions.
16 changes: 16 additions & 0 deletions docs/source/api_doc/utils/cache.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
imgutils.utils.cache
====================================

.. currentmodule:: imgutils.utils.cache

.. automodule:: imgutils.utils.cache



ts_lru_cache
------------------------------

.. autofunction:: ts_lru_cache



1 change: 1 addition & 0 deletions docs/source/api_doc/utils/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,5 @@ imgutils.utils
.. toctree::
:maxdepth: 3

cache
onnxruntime
41 changes: 41 additions & 0 deletions imgutils/utils/cache.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,51 @@
"""
This module provides a thread-safe version of Python's built-in lru_cache decorator.
The main component of this module is the ts_lru_cache decorator, which wraps the standard
lru_cache with thread-safe functionality. This is particularly useful in multi-threaded
environments where cache access needs to be synchronized to prevent race conditions.
Usage:
>>> from imgutils.utils import ts_lru_cache
...
>>> @ts_lru_cache(maxsize=100)
>>> def expensive_function(x, y):
... # Some expensive computation
... return x + y
"""

import threading
from functools import lru_cache

__all__ = ['ts_lru_cache']


def ts_lru_cache(**options):
"""
A thread-safe version of the lru_cache decorator.
This decorator wraps the standard lru_cache with a threading lock to ensure
thread-safety in multithreaded environments. It maintains the same interface
as the built-in lru_cache, allowing you to specify options like maxsize.
:param options: Keyword arguments to be passed to the underlying lru_cache.
:type options: dict
:return: A thread-safe cached version of the decorated function.
:rtype: function
:Example:
>>> @ts_lru_cache(maxsize=100)
>>> def my_function(x, y):
... # Function implementation
... return x + y
.. note::
While this decorator ensures thread-safety, it may introduce some overhead
due to lock acquisition. Use it when thread-safety is more critical than
maximum performance in multithreaded scenarios.
"""

def _decorator(func):
@lru_cache(**options)
def _cached_func(*args, **kwargs):
Expand Down

0 comments on commit 756c977

Please sign in to comment.