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

相关推荐
Bl_a_ck2 分钟前
【React】Craco 简介
开发语言·前端·react.js·typescript·前端框架
子燕若水6 分钟前
Flask 调试的时候进入main函数两次
后端·python·flask
编程有点难6 分钟前
Python训练打卡Day23
开发语言·python
程序员爱钓鱼7 分钟前
跳转语句:break、continue、goto -《Go语言实战指南》
开发语言·后端·golang·go1.19
Z_z在努力8 分钟前
【Redis 进阶】缓存
缓存
hardStudy_h15 分钟前
C程序的存储空间分配
c语言·开发语言
橙子1991101616 分钟前
Kotlin 中的 Unit 类型的作用以及 Java 中 Void 的区别
java·开发语言·kotlin
yours_Gabriel23 分钟前
【登录认证】JWT令牌
java·开发语言·redis
qq_141826973235 分钟前
python通过curl访问deepseek的API调用案例
java·数据库·python
lyw20561936 分钟前
微服务八股(自用)
java·开发语言