#1.普通全局锁

# 2. 支持不同方法的独立锁  (必须有该方法)

 

1.普通全局锁

from functools import wraps
from typing import Dict, Any, List, Optional
import uuid
import tempfile
import shutil
import re
import time

# 历史记录文件
HISTORY_FILE="./history/history.json"
# 全局锁,避免多线程冲突
GLOBAL_LOCK = threading.Lock()
def synchronized_instance_method_with_retry(max_retries=10, delay=0.3, backoff=2, timeout=30):
    """
    高性能版本:针对文件I/O操作优化
    - 优先使用简单锁机制
    - 只在需要时才启用超时监控
    - 减少线程创建频率
    """
    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            last_exception = None

            for attempt in range(max_retries + 1):
                try:
                    with GLOBAL_LOCK:
                        start_time = time.time()

                        # 对于文件操作,通常不需要复杂的超时机制
                        # 因为文件操作通常是同步的
                        result = func(*args, **kwargs)

                        # 如果执行时间超过超时阈值,发出警告
                        execution_time = time.time() - start_time
                        if execution_time > timeout:
                            print(f"Warning: Function took {execution_time:.2f}s (threshold: {timeout}s)")

                        return result

                except Exception as e:
                    last_exception = e
                    print(f"Attempt {attempt + 1} of {max_retries + 1} failed: {e}")
                    if attempt == max_retries:
                        raise last_exception
                    time.sleep(delay * (backoff ** attempt))
            return None
        return wrapper
    return decorator





@synchronized_instance_method_with_retry()
def save(history={},history_file=HISTORY_FILE):
    """
    保存历史记录 把文件写入 本地json文件,可以一直追加,后续可以查询

 

 

 

 

 

 

# 2. 支持不同方法的独立锁  (必须有该方法)

# 支持不同方法的独立锁
def synchronized_instance_method_with_retry(method_name="add", max_retries=30,
                                            timeout=1.0, retry_delay=0.1):
    """
    为每个方法创建独立的实例锁,支持超时重试
    参数:
        method_name: 方法名,用于生成锁属性名
        max_retries: 最大重试次数
        timeout: 每次获取锁的超时时间(秒)
        retry_delay: 重试延迟时间(秒)
    """
    def decorator(func):
        @wraps(func)
        def wrapper(self, *args, **kwargs):
            # 生成锁属性名
            if method_name:
                lock_attr = f"_lock_{method_name}"
            else:
                lock_attr = f"_lock_{func.__name__}"
            # 确保实例有该方法的锁
            if not hasattr(self, lock_attr):
                lock = threading.Lock()
                setattr(self, lock_attr, lock)

            lock = getattr(self, lock_attr)
            retries = 0
            last_exception = None
            while retries <= max_retries:
                acquired = False
                try:
                    # 使用退避算法获取锁
                    acquired = lock.acquire(timeout=timeout)
                    if acquired:
                        return func(self, *args, **kwargs)
                    else:
                        retries += 1
                        if retries <= max_retries:
                            # 指数退避策略
                            wait_time = retry_delay * (2 ** retries)  # 指数增加
                            wait_time = min(wait_time, 5.0)  # 上限5秒
                            print(f"[WARNING] {self.__class__.__name__}.{func.__name__}: "
                                  f"第 {retries} 次重试,等待 {wait_time:.2f}s...")
                            time.sleep(wait_time)
                except Exception as e:
                    last_exception = e
                    if acquired:
                        lock.release()
                    raise e
                finally:
                    if acquired:
                        lock.release()

            error_msg = f"{self.__class__.__name__}.{func.__name__}: 重试 {max_retries} 次后仍失败"
            print(f"[ERROR] {error_msg}")
            raise TimeoutError(error_msg) from last_exception
        return wrapper
    return decorator

使用:

# 支持不同方法的独立锁
def synchronized_instance_method_with_retry(method_name="add", max_retries=30,
                                            timeout=1.0, retry_delay=0.1):
    """
    为每个方法创建独立的实例锁,支持超时重试
    参数:
        method_name: 方法名,用于生成锁属性名
        max_retries: 最大重试次数
        timeout: 每次获取锁的超时时间(秒)
        retry_delay: 重试延迟时间(秒)
    """
    def decorator(func):
         pass


class HistoryUtils:
    def __init__(self, history_file="./history/history.json"):
        #历史记录文件
        self.history_file = history_file
    @synchronized_instance_method_with_retry(method_name="save")
    def save(self, history={},history_file= None):
        """
        保存历史记录 把文件写入 本地json文件,可以一直追加,后续可以查询
        :param history_file: 历史记录文件 eg:./history/history.json
        :param history: 历史记录 eg:{"name": "张三9", "age": 27}    

 

image

 

posted on 2026-01-19 19:42  lshan  阅读(1)  评论(0)    收藏  举报