【发布时间】:2014-04-10 16:52:18
【问题描述】:
我正在尝试针对读者偏好的读写器问题实施解决方案。 以下是问题陈述:
- 数据在一个写入线程和多个读取线程之间共享
- 如果写入线程正在访问共享数据,读取线程应该等待。
- 如果另一个读取器线程正在访问共享数据,读取器线程不应等待
我想出了以下伪代码。
有人能告诉我以下解决方案是否足够,有什么问题吗?
initialize()
{
initialize semaphore with value 0
initialize reader_active_count with value 1
}
writer()
{
// Wait until reader thread makes the semaphore non-zero
sem_wait(s)
write data;
sem_post(s)
}
reader()
{
lock(r1)
reader_active_count ++;
// Am I the first reader thread
if (reader_active_count == 1)
{
// Wait until writer thread makes the semaphore non-zero
sem_wait(s);
}
unlock(r1)
read data
lock(r1)
reader_active_count--;
// Am I the last reader thread
if(reader_active_count == 0)
{
// Increment the sempahore to a non-zero value
sem_post(s);
}
unlock(r1)
}
【问题讨论】: