MST

星途 面试题库

面试题:Python多线程操作Redis数据库时如何处理线程安全问题

在Python中使用多线程操作Redis数据库,由于多个线程可能同时访问和修改Redis中的数据,可能会引发线程安全问题。请描述你知道的处理这种线程安全问题的方法,并给出简单的代码示例。
31.8万 热度难度
编程语言Python

知识考点

AI 面试

面试题答案

一键面试

处理方法

  1. 锁机制:使用threading.Lock,在对Redis进行读或写操作前获取锁,操作完成后释放锁,确保同一时间只有一个线程能访问Redis。
  2. 连接池:使用redis - py库提供的连接池,每个线程从连接池获取连接,避免多个线程竞争连接资源导致问题。

代码示例

import threading
import redis

# 创建Redis连接池
pool = redis.ConnectionPool(host='localhost', port=6379, db=0)
redis_client = redis.Redis(connection_pool=pool)
lock = threading.Lock()


def increment_counter():
    with lock:
        current_value = redis_client.get('counter')
        if current_value is None:
            current_value = 0
        else:
            current_value = int(current_value)
        new_value = current_value + 1
        redis_client.set('counter', new_value)
        print(f'Counter incremented to {new_value}')


# 创建多个线程
threads = []
for _ in range(5):
    t = threading.Thread(target=increment_counter)
    threads.append(t)
    t.start()

# 等待所有线程完成
for t in threads:
    t.join()