缓存与锁:让你的Python代码不仅能飞且安全

什么是缓存?

缓存(Cache)就是把一些耗时的计算结果存起来,下次再用的时候直接拿出来,不用再重新计算。就像你去超市买东西,第一次找货架找得头晕眼花,第二次直接去你记得的地方拿就好了。

为什么要用锁?

在多线程环境中,多个线程可能同时访问和修改缓存,这时候就需要锁(Lock)来确保线程安全。锁就像是超市的保安,确保每次只有一个人能拿货,避免混乱。

cachetools 的 cachedmethod 和 lock

cachetools 是一个强大的缓存库,提供了多种缓存策略。我们今天要用的是 cachedmethod 和 TTLCache,再加上 threading.Lock 来确保线程安全。

实战演练

话不多说,直接上代码!

python 复制代码
import threading
from cachetools import cachedmethod, TTLCache
from cachetools.keys import hashkey

class ExpensiveComputation:
    def __init__(self):
        # 创建一个 TTLCache 对象,设置最大容量为 100,TTL(Time To Live)为 300 秒
        self.cache = TTLCache(maxsize=100, ttl=300)
        # 创建一个锁对象
        self.lock = threading.Lock()

    @cachedmethod(cache=lambda self: self.cache, key=hashkey, lock=lambda self: self.lock)
    def compute(self, x):
        print(f"Computing {x}...")
        return x * x

# 多线程环境下调用
def worker(obj, n):
    print(f"Result for {n}: {obj.compute(n)}")

expensive_computation = ExpensiveComputation()

threads = []
for i in range(5):
    t = threading.Thread(target=worker, args=(expensive_computation, i))
    threads.append(t)
    t.start()

for t in threads:
    t.join()

代码解析

  1. 创建缓存对象和锁对象:
python 复制代码
class ExpensiveComputation:
    def __init__(self):
        self.cache = TTLCache(maxsize=100, ttl=300)
        self.lock = threading.Lock()

在类的构造函数中,我们创建了一个 TTLCache 对象和一个 threading.Lock 对象。TTLCache 的最大容量是 100,缓存项的生存时间是 300 秒。

  1. 使用 cachedmethod 装饰器:
python 复制代码
@cachedmethod(cache=lambda self: self.cache, key=hashkey, lock=lambda self: self.lock)
def compute(self, x):
    print(f"Computing {x}...")
    return x * x

使用 cachedmethod 装饰器装饰 compute 方法,并传入 cache 和 lock 参数。cache 参数使用 lambda self: self.cache 形式,以便在实例方法中访问实例属性。lock 参数同样使用 lambda self: self.lock 形式。

  1. 多线程调用:
python 复制代码
def worker(obj, n):
    print(f"Result for {n}: {obj.compute(n)}")

expensive_computation = ExpensiveComputation()

threads = []
for i in range(5):
    t = threading.Thread(target=worker, args=(expensive_computation, i))
    threads.append(t)
    t.start()

for t in threads:
    t.join()

创建多个线程并调用 compute 方法,验证缓存的线程安全性。

总结:

通过结合 cachetools 的 cachedmethod 装饰器、TTLCache 和 threading.Lock,我们实现了线程安全且带有过期时间的类方法缓存。这样,你的代码不仅跑得更快,还能在多线程环境中稳如泰山。

相关推荐
持梦远方1 分钟前
C 语言基础入门:基本数据类型与运算符详解
c语言·开发语言·c++
zzywxc78718 分钟前
AI 正在深度重构软件开发的底层逻辑和全生命周期,从技术演进、流程重构和未来趋势三个维度进行系统性分析
java·大数据·开发语言·人工智能·spring
en-route23 分钟前
HTTP 缓存
网络协议·http·缓存
3gying35 分钟前
chromedriver
python
灵性花火37 分钟前
Qt的前端和后端过于耦合(0/7)
开发语言·前端·qt
DES 仿真实践家1 小时前
【Day 11-N22】Python类(3)——Python的继承性、多继承、方法重写
开发语言·笔记·python
Code Warrior3 小时前
【每日算法】专题五_位运算
开发语言·c++
沐知全栈开发5 小时前
HTML DOM 访问
开发语言
脑袋大大的6 小时前
JavaScript 性能优化实战:减少 DOM 操作引发的重排与重绘
开发语言·javascript·性能优化
云泽野6 小时前
【Java|集合类】list遍历的6种方式
java·python·list