c++ - 为什么在此代码块中使用 condition_variable?

标签 c++ multithreading c++11 condition-variable

我是条件变量的新手,我想知道为什么计数器变量等于 99 之后的这段代码块? 删除for循环并改用“counter += 99”使代码工作,它与sleep_for有什么关系吗?感谢您的帮助:)

#include<thread>
#include<condition_variable>
#include<mutex>
#include<chrono>
#include <iostream>
std::condition_variable cv;
std::mutex mtx;
int counter = 0;

void foo() {
    std:: unique_lock<std::mutex>lck{ mtx };
    //counter += 99;
    for (; counter < 100; counter++) {
        std::cout << counter << std::endl;
        std::this_thread::sleep_for(std::chrono::milliseconds(20));
    }
    lck.unlock();
    cv.notify_one();
}

int main() {
    std::thread th(&foo);
    {
        std::unique_lock<std::mutex>lck{ mtx };
        cv.wait(lck, [] {
            return counter == 99;
        });
    }

    std::cout << "!!!!!" << std::endl;
    th.join();
}

最佳答案

让我们为您的代码添加一些注释:

void foo() {
    std:: unique_lock<std::mutex>lck{ mtx };
    // counter == 0
    for (; counter < 100; counter++) {
        ...
    }
    // counter == 100
    lck.unlock();
    cv.notify_one(); // <== notify here
}

我们循环直到 counter == 100 ,此时我们通知cv .然而,我们正在等待counter == 99 ,在收到通知时并非如此。 wait() 的唯一方法在您的代码中返回是为了在循环的最后一次迭代时发生虚假唤醒。

也许你打算循环 while counter < 99 .

关于c++ - 为什么在此代码块中使用 condition_variable?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32615223/

相关文章:

c++ - 是否可以将模板实例视为命名空间?

java - 在 Java 中停止线程的安全方法

c++ - 创建动态大小的对象

c++ - 为什么不支持从 template<typename T1, typename T2> 到 template<typename T1, int i> 的类特化

当我将 log4j 附加到文本区域时,JavaFX 应用程序卡住

c++ - 将 std::async 与需要函数和参数参数的函数一起使用

c++ - gcc 和 MSFT CL 之间的位域结构大小不同

c++ - 用于 g++ 编译的 C++ 文件的用户定义扩展

c++ - 在 C++ 中将数字转换为字符串的最佳方法?

c++ - 数组结构和结构数组 - 性能差异