读写锁的实现
我有一个家庭作业问题,我必须实现读写锁。请注意,我不是在寻找/索要代码。我希望了解读写锁的行为,这将帮助我最终确定实现细节。
假设获取锁的请求遵循以下顺序:RWRWRWR W.. 为了防止饥饿,我们应该以相同的顺序处理请求吗?如果我选择跳过写请求(从而为读者提供更高的优先级),如何确保编写者线程不会挨饿?
如果给作者更高的偏好,我认为读者线程可能会挨饿。
我认为我当前的计划适用于 RRRRWRRRRWWWRRRRR、WWWWWRRRRWRRRR、RRRRRRRR、WWWWWWWW、RWRRR、WRWWWW 等序列。
还有其他我没有考虑的情况吗? - 我知道这是一个很难回答的问题,尤其是。因为我没有透露任何细节,也没有列举我考虑过的所有场景。请多多包涵!
I have a homework problem where I have to implement a reader writer lock. Please note that I am NOT looking/asking for code. I wish to understand the behaviour of reader-writer locks which will help me finalize the implementation details.
Lets say the request for acquiring the locks follows this sequence: R W R W R W R W..
In order to prevent starvation, should we process the requests in the same order? If I choose to jump over a write request (thus giving readers a higher preference), how can I ensure that a writer thread will not starve?
If give writers a higher preference instead, I think there is chance that reader threads will starve.
I think my current plan will work for sequences like RRRRWRRRRWWWRRRRR, WWWWWWRRRRWRRRR, RRRRRRR, WWWWWWW, RWRRR, WRWWWW and so on.
Are there any other scenarios I am not considering? - I know this is a tough one to answer esp. since I am not disclosing any details and haven't enumerated all scenarios I considered. Please bear with me!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当等待时间没有限制时,“更高优先级”只会产生饥饿。
如果任何线程可以等待的时间限制为某个有限值,则该线程将不会挨饿。
因此,只要您跟踪线程何时进入队列并以某种方式不让它们等待“太久”,您就可以在一般情况下(或相反)“优先考虑读者而不是作家”,同时仍然不会导致活锁。
通过在选择作家之前仅服务最大数量的读者可以获得相同的效果,反之亦然。
"Higher priority" can only produce starvation when there is no bound on the wait time.
If the amount of time for which any thread can wait is bounded to some finite value, that thread will not starve.
So, as long as you keep track of when threads enter the queue and somehow don't let them wait "too long", you can "prioritize readers over writers" in the general case (or the reverse), while still not causing a livelock.
The same effect can be gotten by only servicing a maximal number of readers before taking a writer, or vice versa.
读写器系统中饥饿的常见原因是“共享”锁的存在,这些锁允许多个读取器锁定同一资源。
如果优先考虑其中一个很简单,那么您可以简单地有两个队列,一个用于读者,一个用于作者,并为每个 Y 个作者(如果有等待)提供 X 个读者(如果有正在等待)。
The usual reason for starvation in a reader-writer system is the presence of "shared" locks, locks allowing multiple readers to lock the same resource.
If it's simple a matter of giving preference to one or the other, you could simply have two queues, one for readers and one for writers, and serve X readers (if any are waiting) for every Y writers (if any waiting).