[英]how to make boost upgrade_to_unique_lock + condition_variable work together?
I use a std::list to hold some string, one thread writes to the list and some other threads read from it(get the first and erase from the list). 我使用一个std :: list来保存一些字符串,一个线程写入列表,而其他一些线程从列表中读取(获取第一个并从列表中删除)。 Here's the code:
这是代码:
std::list<string> list_;
boost::condition_variable cond;
boost::shared_mutex mtx;
int get_size() {
boost::shared_lock<boost::shared_mutex> lock(mtx);
return list_.size();
}
// add a string to the list
// invoked by only one thread
void add_one(const string& p) {
{
boost::upgrade_lock<boost::shared_mutex> lock(mtx);
boost::upgrade_to_unique_lock<boost::shared_mutex> uniquelock(lock);
list_.push_back(p);
}
cond.notify_one();
}
// get the first string and remove it from the list
// invoked by many threads
string pick_one() {
string ret;
{
boost::upgrade_lock<boost::shared_mutex> lock(mtx);
boost::upgrade_to_unique_lock<boost::shared_mutex> uniquelock(lock);
if(!list_.size()) { // if empty, wait for notify
cond.wait(uniquelock, [&]{ return list_.size() > 0; }); // compile error
}
ret = list_.front();
list_.pop_front();
}
return ret;
}
There's compile error at line cond.wait(uniquelock, ...
cond.wait(uniquelock, ...
What's the correct way of using read/write lock with condition_variable? 在condition_variable中使用读/写锁定的正确方法是什么?
You cannot do this - upgrade_to_unique_lock
is a RAII helper to obtain exclusive access on the lock for its lifetime. 您无法执行此操作
upgrade_to_unique_lock
是RAII的帮助程序,可在其生命周期内获得对该锁的独占访问。 See docs here . 在这里查看文档。
boost::upgrade_to_unique_lock allows for a temporary upgrade of an boost::upgrade_lock to exclusive ownership.
boost :: upgrade_to_unique_lock允许将boost :: upgrade_lock临时升级到独占所有权。 When constructed with a reference to an instance of boost::upgrade_lock, if that instance has upgrade ownership on some Lockable object, that ownership is upgraded to exclusive ownership.
当参考boost :: upgrade_lock实例构造时,如果该实例在某个Lockable对象上具有升级所有权,则该所有权将升级为独占所有权。 When the boost::upgrade_to_unique_lock instance is destroyed, the ownership of the Lockable is downgraded back to upgrade ownership.
当boost :: upgrade_to_unique_lock实例被破坏时,Lockable的所有权将降级以升级所有权。
If you wish to use shared_mutex
with a Boost condition variable you must use boost::condition_variable_any
as described here . 如果您希望使用
shared_mutex
与升压条件变量必须使用boost::condition_variable_any
描述这里 。 The difference between the two conditional variables (albeit in reference to std
, not Boost
) is covered here . 这里涵盖了两个条件变量之间的差异(尽管参考了
std
,而不是Boost
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.