简体   繁体   English

使用Writer模块的Boost中的多读取器,单写入器锁定

[英]Multiple-Reader, Single-Writer Lock in Boost WITH Writer Block

The answer here almost does what I want. 答案在这里 几乎是我想要做什么。

I want a read-write lock that will: 我想要一个读写锁,它将:

  1. Allow readers to take the lock as long as there is no writer 只要没有作家,就允许读者采取锁定措施
  2. If a writer tries the lock, block out new readers from taking it but allow old readers to finish before giving the writer the lock 如果作者尝试使用该锁,请阻止新读者使用它,但允许老读者在给作者锁之前完成操作
  3. Once the writer releases the lock, allow new readers 一旦作者解除锁定,请允许新读者

The implementation above does not meet criteria (2). 上面的实现不符合条件(2)。 It allows new readers to grab the lock and block out the writer until they are finished. 它允许新的读者抓住锁并阻止作家,直到他们完成。

Found it. 找到了。 I needed unique_lock instead of upgrade_to_unique_lock : 我需要unique_lock而不是upgrade_to_unique_lock

boost::shared_mutex _access;
void reader()
{
    // get shared access
    boost::shared_lock<boost::shared_mutex> lock(_access);
}

void writer()
{
    // wait for old shared access readers to finish
    // but block out new shared access readers
    boost::unique_lock<boost::shared_mutex> uniqueLock(_access);
}

But here your "writer" method does not have a "lock" attribute. 但是,这里的“ writer”方法没有“ lock”属性。 Do you mean that before the "unique_lock" you still need to do the "upgrade_lock"? 您是说在“ unique_lock”之前您还需要进行“ upgrade_lock”吗? Something like: 就像是:

void writer()
{
    // get upgradable access
    boost::upgrade_lock<boost::shared_mutex> lock(_access);

    // get exclusive access
    boost::unique_lock<boost::shared_mutex> uniqueLock(lock);
    // now we have exclusive access
}

Or did you mix attributes and it should be: 还是您混合了属性,应该是:

void writer()
{
    boost::unique_lock<boost::shared_mutex> uniqueLock(_access);
    // now we have exclusive access
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM