如何在不指定信号量资源计数的情况下创建 ReadWriteMutex?
ReadWriteMutex 的通常模式是使用信号量并让 writer 循环获取所有资源:
inline void write_lock() {
ScopedLock lock(acquire_mutex_);
for (size_t i=0; i < resource_count_; ++i) {
if (sem_wait(semaphore_) < 0) {
fprintf(stderr, "Could not acquire semaphore (%s)\n", strerror(errno));
}
}
}
这很好,只是您必须在信号量初始化期间指定资源计数,并且任意选择 10 或 99999 的资源计数并不感觉正确的。是否有更好的模式可以允许“无限”读者(不需要资源计数)?
The usual pattern for a ReadWriteMutex is to use a semaphore and have the writer loop to acquire all the resources:
inline void write_lock() {
ScopedLock lock(acquire_mutex_);
for (size_t i=0; i < resource_count_; ++i) {
if (sem_wait(semaphore_) < 0) {
fprintf(stderr, "Could not acquire semaphore (%s)\n", strerror(errno));
}
}
}
This is fine except that you have to specify the resource count during semaphore initialization and arbitrarily choosing a resource count of 10 or 99999 does not feel right. Is there a better pattern that would allow "infinite" readers (no need for a resource count) ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我找到了一个解决方案:使用
pthread_rwlock_t
(Windows 上的 ReaderWriterLock)。这些锁不需要特定的“max_readers_count”。我怀疑这个锁的实现使用某种条件变量来锁定读取器条目,当写入器需要写入和原子读取器计数时。
将此与我自制的基于信号量的锁进行比较表明,编写者受到青睐(他们倾向于先运行)。
I found a solution: using
pthread_rwlock_t
(ReaderWriterLock on Windows). These locks do not require a specific 'max_readers_count'.I suspect that the implementation for this lock uses some kind of condition variable to lock readers entry when a writer needs to write and an atomic reader count.
Comparing this with my homebrewed semaphore based lock shows that writers are favored (they tend to run first).