读者一写者问题python
时间: 2024-10-29 22:14:43 浏览: 6
"Reader-Writer Problem",也称为“读写锁”或“共享-独占锁”,是一个经典的并发控制问题,特别是在Python这样的多线程环境中。当有多个线程同时读取数据时,可以允许多个读线程同时访问,而只有一个写线程能够写入以防止数据冲突。这通过`threading.Lock()`或者其他类似机制(如`threading.RLock()`,它提供了一种更细粒度的锁定,允许读锁并行存在)来实现。
在Python中,你可以这样做:
1. 使用`RLock`(可重入读锁):
```python
import threading
data = "initial data"
lock = threading.RLock()
def reader():
with lock.read_lock(): # 获取读锁,允许其他读操作
print(data)
def writer():
with lock.write_lock(): # 获取写锁,禁止其他读写操作
data = "new data"
```
2. 使用`threading.Lock()`:
```python
data = "initial data"
lock = threading.Lock()
def reader():
lock.acquire(read_lock=True) # 获取读锁
try:
print(data)
finally:
lock.release() # 确保释放锁
def writer():
lock.acquire(write_lock=True) # 获取写锁
try:
data = "new data"
finally:
lock.release()
```
阅读全文