操作系统 读者-写者问题源代码和注释
时间: 2024-10-21 13:14:44 浏览: 42
操作系统中的"读者-写者问题"(Reader-Writer Problem),也称为Bounded Buffer问题,是一个经典的并发控制问题,主要用于解决多个读进程和一个写进程如何安全地共享缓冲区的问题。这个问题的主要目的是避免数据竞争,确保任何时候只有一个进程能修改缓冲区。
这里给出一个简单的Python版本的线程同步解决方案,使用了`threading.Lock()`来保证互斥访问,`threading.Condition()`来协调读写操作:
```python
import threading
class SharedBuffer:
def __init__(self, capacity):
self.capacity = capacity
self.buffer = [None] * capacity
self.head = 0
self.tail = 0
self.lock = threading.Lock()
self.condition = threading.Condition(self.lock)
# 插入操作,写者任务
def writer(self, data):
with self.lock:
while self.is_full():
self.condition.wait() # 阻塞直到有读取空间
self.buffer[self.tail] = data
self.tail = (self.tail + 1) % self.capacity
self.condition.notify_all() # 唤醒所有等待的读者
# 读取操作,读者任务
def reader(self):
with self.lock:
while self.is_empty():
self.condition.wait() # 阻塞直到有内容可读
data = self.buffer[self.head]
self.head = (self.head + 1) % self.capacity
return data
# 返回并释放锁,唤醒可能等待的其他读者
def is_empty(self):
return self.head == self.tail
def is_full(self):
return (self.tail + 1) % self.capacity == self.head
# 示例:
buffer = SharedBuffer(5)
writer_thread = threading.Thread(target=buffer.writer, args=("Data1",))
reader_thread1 = threading.Thread(target=buffer.reader)
reader_thread2 = threading.Thread(target=buffer.reader)
writer_thread.start()
reader_thread1.start()
reader_thread2.start()
writer_thread.join()
reader_thread1.join()
reader_thread2.join()
```
阅读全文