线程安全的数据结构在 Python 中的实现有哪些(如 `queue.Queue`)?如何自己实现一个线程安全的缓存机制?

线程安全的数据结构在 Python 中主要通过 threading 模块和标准库提供的一些类实现。以下是常见的线程安全数据结构及其实现方式,以及如何自己实现一个线程安全的缓存机制。

1. 常见的线程安全数据结构

  1. queue.Queue queue.Queue 是 Python 中线程安全的先进先出(FIFO)队列,基于 threading 模块的锁机制实现。以下是其使用示例:

    import queue
    import threading
    
    # 创建一个线程安全的队列
    q = queue.Queue()
    
    def worker():
        while True:
            item = q.get()
            print(f"处理: {item}")
            q.task_done()
    
    # 启动多个线程
    for i in range(3):
        t = threading.Thread(target=worker)
        t.daemon = True
        t.start()
    
    # 添加任务
    for item in range(10):
        q.put(item)
    
    q.join()  # 等待所有任务完成
    
  2. collections.deque 配合锁 collections.deque 虽然是线程安全的,但为了实现更复杂的操作(如检查非空后再取值),通常需要配合 threading.Lock 使用。示例:

    from collections import deque
    import threading
    
    dq = deque()
    lock = threading.Lock()
    
    def safe_append(value):
        with lock:
            dq.append(value)
    
    def safe_pop():
        with lock:
            return dq.pop() if dq else None
    
  3. threading.Lock 保护共享变量 对于简单的共享变量,可以使用 threading.Lock 来确保线程安全。例如:

    counter = 0
    lock = threading.Lock()
    
    def increment():
        global counter
        with lock:
            counter += 1
    

2. 实现一个线程安全的缓存机制

以下是一个基于 dict 和 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, None)

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

    def clear(self):
        with self.lock:
            self.cache.clear()

# 使用示例
cache = ThreadSafeCache()
cache.set("name", "Alice")
print(cache.get("name"))  # 输出: Alice

进一步优化:LRU 缓存

如果需要更复杂的缓存机制(如 LRU 缓存),可以结合 collections.OrderedDict 和锁实现:

from collections import OrderedDict
import threading

class LRUCache:
    def __init__(self, capacity):
        self.capacity = capacity
        self.cache = OrderedDict()
        self.lock = threading.Lock()

    def get(self, key):
        with self.lock:
            if key not in self.cache:
                return None
            self.cache.move_to_end(key)
            return self.cache[key]

    def set(self, key, value):
        with self.lock:
            if key in self.cache:
                self.cache.move_to_end(key)
            self.cache[key] = value
            if len(self.cache) > self.capacity:
                self.cache.popitem(last=False)

# 使用示例
lru_cache = LRUCache(2)
lru_cache.set("a", 1)
lru_cache.set("b", 2)
print(lru_cache.get("a"))  # 输出: 1
lru_cache.set("c", 3)      # "b" 被淘汰
print(lru_cache.get("b"))  # 输出: None