Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why this conditon variable is not working?

I was trying to understand the condition_variable available in C++ standard. So in the below test code I have written, I expect the func1 to be woken up after printing 50 numbers in main thread but here it prints all numbers only from main thread?

Could you please help me here to understand condition_variable better to indicate a certain thread to wake up

I have tried to understand condition variable using below code:

#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;
}
like image 298
StraightCirle Avatar asked Mar 13 '26 02:03

StraightCirle


1 Answers

You never release mu in main thread. Try something like this:

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

In general you need to keep your locks for absolute minimum of time you can.

like image 161
Radosław Cybulski Avatar answered Mar 15 '26 15:03

Radosław Cybulski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!