面试题答案
一键面试- 阐述优化方法:
- 使用锁机制(如
threading.Lock
)来确保在同一时间只有一个线程能够访问和修改缓存字典。当一个线程获取锁后,它可以安全地对字典进行读取、写入或删除操作,操作完成后释放锁,其他线程才能获取锁进行操作。这样就避免了多个线程同时修改字典导致的数据不一致问题。
- 使用锁机制(如
- 示例代码:
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
来保护对字典的操作。get
和set
方法都使用with self.lock
语句块来自动获取和释放锁,确保了在多线程环境下缓存操作的线程安全。测试代码通过创建多个线程来调用set
和get
方法,验证缓存的线程安全性。