MST

星途 面试题库

面试题:Python字典缓存的优化与并发控制

在多线程环境下使用Python字典进行缓存,可能会出现竞争条件。请阐述如何优化缓存字典的使用以避免竞争条件,并且写出一个简单的示例代码,使用适当的同步机制(如锁)来保证缓存操作的线程安全。
20.5万 热度难度
编程语言Python

知识考点

AI 面试

面试题答案

一键面试
  1. 阐述优化方法
    • 使用锁机制(如threading.Lock)来确保在同一时间只有一个线程能够访问和修改缓存字典。当一个线程获取锁后,它可以安全地对字典进行读取、写入或删除操作,操作完成后释放锁,其他线程才能获取锁进行操作。这样就避免了多个线程同时修改字典导致的数据不一致问题。
  2. 示例代码
import threading


class ThreadSafeCache:
    def __init__(self):
        self.cache = {}
        self.lock = threading.Lock()

    def get(self, key):
        with self.lock:
            return self.cache.get(key)

    def set(self, key, value):
        with self.lock:
            self.cache[key] = value


# 测试代码
def worker(cache, key, value):
    cache.set(key, value)
    result = cache.get(key)
    print(f"Thread {threading.current_thread().name} got value: {result}")


cache = ThreadSafeCache()
threads = []
for i in range(5):
    t = threading.Thread(target=worker, args=(cache, f"key_{i}", f"value_{i}"))
    threads.append(t)
    t.start()

for t in threads:
    t.join()

在上述代码中,ThreadSafeCache类封装了一个字典作为缓存,并使用threading.Lock来保护对字典的操作。getset方法都使用with self.lock语句块来自动获取和释放锁,确保了在多线程环境下缓存操作的线程安全。测试代码通过创建多个线程来调用setget方法,验证缓存的线程安全性。