在下面的例子中:
工作线程向 vector 添加一些东西:
std::lock_guard<std::mutex> guard(UI::GetInstance().my_mutex);
UI::GetInstance().my_vector.push_back(new_value);
UI 线程检查列表:
while (true) {
std::lock_guard<std::mutex> guard(my_mutex);
//perform my_vector operations and clear at the end
my_vector.clear();
}
我不喜欢每次迭代都进行锁保护,是否有更好的方法?我希望像这样设置某种标志,但我不确定 bool 是否是线程安全的:
工作线程向 vector 添加一些东西:
std::lock_guard<std::mutex> guard(UI::GetInstance().my_mutex);
UI::GetInstance().my_vector.push_back(new_value);
UI::GetInstance().my_vector_changed=true; // set a flag
UI 线程检查列表:
while (true) {
if (my_vector_changed) { // only lock on changes
std::lock_guard<std::mutex> guard(my_mutex);
//perform my_vector operations and clear at the end
UI::GetInstance().my_vector.clear();
my_vector_changed=false;
}
}
是否有更好的锁守卫方法?
最佳答案
这种“有人对受该互斥体保护的数据做了一些有趣的事情”通知是条件变量的用途——使用 condition_variable
相反。
关于您的技术:这有点像滚动您自己的简历,但如果您这样做,一定要做到 bool
是atomic<bool>
或 atomic_flag
因为对它的访问需要同步,有时需要等待而不是旋转(不断轮询)。
关于c++ - C++11 中的线程 : A better way to approach lock guards?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17412595/