C++中的线程11:接近锁定防护的更好方法是什么?

Gra*_*pes 2 c++ multithreading thread-safety c++11

在以下示例中:

工作线程向向量添加了一些东西:

std::lock_guard<std::mutex> guard(UI::GetInstance().my_mutex);

UI::GetInstance().my_vector.push_back(new_value);
Run Code Online (Sandbox Code Playgroud)

UI Thread检查列表:

while (true) {
    std::lock_guard<std::mutex> guard(my_mutex);

    //perform my_vector operations and clear at the end
    my_vector.clear();
}
Run Code Online (Sandbox Code Playgroud)

我不喜欢锁定每次迭代,有没有更好的方法呢?我希望设置一些像这样的标志,但我不确定bool是否是线程安全的:

工作线程向向量添加了一些东西:

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
Run Code Online (Sandbox Code Playgroud)

UI Thread检查列表:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

是否有更好的方法来锁定守卫?

Her*_*ter 6

这种"有人对受互斥锁保护的数据做了一些有趣的事情"通知是条件变量的用途 - condition_variable改为使用.

回复你的技术:这是一种像滚动您自己的简历,但如果你这样做,一定要做出boolatomic<bool>atomic_flag因为访问它需要被同步,并等待纺(不断轮询)有时代替.

  • @Grapes:如果有(在任何给定的实现上),那是因为使用`bool`不起作用.一般来说,最好不要对快速破解的代码感到非常兴奋;-) (6认同)