2

在以下示例中:

工作线程向向量添加一些内容:

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();
}

我不喜欢每次迭代都保护锁,有更好的方法吗?我希望像这样设置某种标志,但我不确定布尔值是否是线程安全的:

工作线程向向量添加一些内容:

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;
    }
}

有没有更好的方法来锁定警卫?

4

1 回答 1

6

这种“有人对受该互斥锁保护的数据做了一些有趣的事情”通知就是条件变量的用途——改用 a condition_variable

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

于 2013-07-01T20:43:19.293 回答