维基百科的读写锁实现是否正确?

Is Wikipedia's read-write lock implementation correct?

我正在使用 SDL 线程和互斥锁在 C 中实现 write-preferring R/W 锁。我checked Wikipedia for a pseudo-code implementation:


Reader 和 Writer 的输入:mutex mu,条件变量 cond,整数 readersWaiting=0 和 boolean writerWaiting=false。

Reader:

  • Lock mu
  • While writerWaiting is true:
    • wait cond, mu[a]
  • Increment readersWaiting
  • Read operation
  • Decrement readersWaiting
  • While readersWaiting > 0:
    • wait cond, mu
  • Notify cond (signal)
  • Unlock mu

Writer:

  • Lock mu
  • While writerWaiting is true:
    • wait cond, mu
  • Write operation
  • Set writerWaiting to true
  • While readersWaiting > 0:
    • wait cond, mu
  • Set writerWaiting to false
  • Notify cond (broadcast)
  • Unlock mu

我认为 SDL 满足此要求

wait: This is the standard "wait" operation on condition variables, which, among other actions, releases the mutex m

我的问题是,这是正确的吗?因为我用一个消费者线程和一个或多个生产者线程尝试了这个,但它没有用;消费者会阻塞并且队列不会为空。我很确定我的实现与伪代码相同,但我最终想出了我自己的系统。

现在想想,可能是我读操作处理空队列的原因。

另外,有人能解释一下文章中的这句话是什么意思吗?

Each of lock-for-read and lock-for-write has its own inverse operation.

该实现在很多方面都被严重破坏。我只指出最明显的一点:读者会在持有锁的同时进行阅读。所以它甚至无法支持多个并发阅读器!

鉴于它实际上根本不是 readers/writer 锁,分析它的其他问题似乎毫无意义。不出所料,它也不偏爱作者,因为作者在没有读者之前无法将 writerWaiting 设置为 true。

顺便说一句,那个页面上的两个互斥体实现也被严重破坏了。 *感叹*