c++mutexcondition-variable

How do condition variable and mutex work in C++?


#include <thread>
#include <mutex>
#include <condition_variable>
#include <iostream>
#include <chrono>
using namespace std;
using namespace std::chrono_literals;

condition_variable cv;
mutex mu;

void thread1()
{
    mu.lock();
    unique_lock lck(mu);
    cv.wait(lck);
    cout << 1;
}

void thread2()
{
    this_thread::sleep_for(1s);
    mu.lock();
    cv.notify_all();
    cout << 2;    
}

int main()
{
    thread t1(thread1);
    thread t2(thread2);
    this_thread::sleep_for(2s);
}

This code was expected to show number 1 and 2, but shows nothing. If a condition variable has waited with a mutex, then the mutex is unlocked, right?


Solution

  • Several issues with the code:

    Closer to what you want:

    
    condition_variable cv;
    mutex mu;
    bool has_value_been_set = false;
    int value = 0;
    
    void thread1()
    {
        unique_lock<mutex>lck(mu);
        while (has_value_been_set == false)
        {
            cv.wait(lck);
        }
        
        cout << "thread1: the value set by the other thread is: " << value << "\n";
    
    }
    void thread2()
    {
        sleep(1);
        {
            unique_lock<mutex>lck(mu);
            value = 42;
            has_value_been_set = true;
            cout << "thread2: setting the value: " << value << "\n";
        }
    
        cout << "thread2: notifying other threads: " << value << "\n";
        cv.notify_all();
    
        
    }
    int main()
    {
        thread t1(thread1);
        thread t2(thread2);
    
    
        // wait for both threads to be done
        t1.join();
        t2.join();
    
    }