缓存与锁:让你的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,我们实现了线程安全且带有过期时间的类方法缓存。这样,你的代码不仅跑得更快,还能在多线程环境中稳如泰山。

相关推荐
沐知全栈开发2 小时前
HTML DOM 访问
开发语言
脑袋大大的3 小时前
JavaScript 性能优化实战:减少 DOM 操作引发的重排与重绘
开发语言·javascript·性能优化
云泽野4 小时前
【Java|集合类】list遍历的6种方式
java·python·list
二进制person4 小时前
Java SE--方法的使用
java·开发语言·算法
OneQ6664 小时前
C++讲解---创建日期类
开发语言·c++·算法
IMPYLH5 小时前
Python 的内置函数 reversed
笔记·python
码农不惑5 小时前
2025.06.27-14.44 C语言开发:Onvif(二)
c语言·开发语言
Coding小公仔7 小时前
C++ bitset 模板类
开发语言·c++
小赖同学啊7 小时前
物联网数据安全区块链服务
开发语言·python·区块链
shimly1234567 小时前
bash 脚本比较 100 个程序运行时间,精确到毫秒,脚本
开发语言·chrome·bash