c++ - C++11 中的线程 : A better way to approach lock guards?

标签 c++ multithreading c++11 thread-safety

在下面的例子中:

工作线程向 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相反。

关于您的技术:这有点像滚动您自己的简历,但如果您这样做,一定要做到 boolatomic<bool>atomic_flag因为对它的访问需要同步,有时需要等待而不是旋转(不断轮询)。

关于c++ - C++11 中的线程 : A better way to approach lock guards?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17412595/

相关文章:

c++ - 动态数组类,程序运行良好但出现错误

c++ - 如何将 std::map::operator= 与初始化列表一起使用

java - 避免在对 JButton 执行操作后卡住

ios - 在 ios 上重新启动后台选择器

c++ - 在将实例作为基础对象传递的函数中使用复制构造函数创建实例的拷贝

c++ - 返回 nullptr 迭代器,如何转换它们

c++ - 我正在尝试制作字符串函数的 HashMap

c++ - 返回 NULL 而不是 std::string C++

c++ - C++ 中的 static const 与 #define - 可执行文件大小的差异

java - 为什么我的 Java 线程似乎只在一个核心上运行,而我的机器有两个核心?