为什么这个条件变量不起作用

Why this conditon variable is not working?

本文关键字:变量 不起作用 条件 为什么      更新时间:2023-10-16

我试图理解C++标准中可用的condition_variable。所以在我写的下面的测试代码中,我希望在主线程中打印 50 个数字后唤醒func1,但这里它只打印主线程中的所有数字?

您能否在这里帮助我更好地理解condition_variable更好地指示要唤醒的某个线程

我试图使用以下代码来理解条件变量:

#include <stdio.h>
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
using namespace std;
std::mutex mu;
std::condition_variable multiple;
bool isLoaded = false;
void func1()
{
    std::unique_lock<std::mutex> unLock(mu);
    multiple.wait(unLock, []() {return isLoaded; });
    for (int i = 0; i < 100; i++)
    {        
        cout << "This is from thread; " << i << endl;                
    }
}
int main()
{
    std::thread t1(func1);
    std::lock_guard<std::mutex> gaurd(mu);
    cout << std::thread::hardware_concurrency()<< endl;
    for (int i = 0; i < 100; i++)
    {
        if (i == 50)
        {
            isLoaded = true;
            multiple.notify_one();
            std::this_thread::sleep_for(std::chrono::seconds(4));
        }
        cout << "This is from main; " << i << endl;
    }
    t1.join();
    getchar();
    return 0;
}

您永远不会在主线程中释放mu。尝试这样的事情:

int main()
{
    std::thread t1(func1);
    cout << std::thread::hardware_concurrency()<< endl;
    for (int i = 0; i < 100; i++)
    {
        if (i == 50)
        {
            {
                std::lock_guard<std::mutex> gaurd(mu);
                isLoaded = true;
            }
            multiple.notify_one();
            std::this_thread::sleep_for(std::chrono::seconds(4));
        }
        cout << "This is from main; " << i << endl;
    }
    t1.join();
    getchar();
    return 0;
}

一般来说,您需要在绝对最短的时间内保持锁。

你在程序开始时采用互斥锁mu并且永远不会放手,所以这个互斥锁下的任何其他代码都不会被执行。

相反,您应该仅在更改共享变量时保留它,例如:

    {
        std::lock_guard<std::mutex> gaurd(mu);
        isLoaded = true;
        multiple.notify_one();
    }