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

相关推荐
Hylan_J2 小时前
【VSCode】MicroPython环境配置
ide·vscode·python·编辑器
软件黑马王子2 小时前
C#初级教程(4)——流程控制:从基础到实践
开发语言·c#
莫忘初心丶2 小时前
在 Ubuntu 22 上使用 Gunicorn 启动 Flask 应用程序
python·ubuntu·flask·gunicorn
闲猫2 小时前
go orm GORM
开发语言·后端·golang
李白同学4 小时前
【C语言】结构体内存对齐问题
c语言·开发语言
黑子哥呢?5 小时前
安装Bash completion解决tab不能补全问题
开发语言·bash
失败尽常态5235 小时前
用Python实现Excel数据同步到飞书文档
python·excel·飞书
2501_904447745 小时前
OPPO发布新型折叠屏手机 起售价8999
python·智能手机·django·virtualenv·pygame
青龙小码农5 小时前
yum报错:bash: /usr/bin/yum: /usr/bin/python: 坏的解释器:没有那个文件或目录
开发语言·python·bash·liunx
大数据追光猿5 小时前
Python应用算法之贪心算法理解和实践
大数据·开发语言·人工智能·python·深度学习·算法·贪心算法