0
我正試圖爲讀者偏好的讀者 - 作者問題實施解決方案。 以下是問題陳述:針對讀者偏好的讀者 - 作者實現解決方案
- 數據一個作家線程和多個讀線程
- 讀線程之間共享,如果作家線程訪問共享數據應該等待。如果另一個讀者線程正在訪問共享數據
我想出了下面的僞代碼
有人可以告訴我,下面的解決方案是否足夠,它有什麼問題?
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)
}
感謝您的評論。 在你提到的場景中,線程3應該釋放信號量,因爲只有當reader_active_count達到0時纔會釋放信號量。 –
@AchintMehta:是的。唯一一次有競爭狀態是線程3被阻塞等待第一個鎖,而線程1在清理過程中被鎖定。然後,線程1將成爲最後一個閱讀器並釋放信號量,讓線程2在線程3增加'reader_active_count'之前獲取它。 –