0

I have experimented to modify C++ example code of condition_variable so that the variable is notified before waiting is initiated. I end up with the code, where I do not notify at all but all the threads are awake.

#include <iostream>
#include <condition_variable>
#include <thread>
#include <chrono>
 
std::condition_variable cv;
std::mutex cv_m; // This mutex is used for three purposes:
                 // 1) to synchronize accesses to i
                 // 2) to synchronize accesses to std::cerr
                 // 3) for the condition variable cv
int i = 0;
 
void waits(int id)
{
    std::this_thread::sleep_for(std::chrono::seconds(2));
    std::unique_lock<std::mutex> lk(cv_m);
    for (int t=10; t!=0; t--)
    {
        std::cerr << id << " waiting " << t <<" seconds... \n";
        std::this_thread::sleep_for(std::chrono::seconds(1));
    }
    // cv.wait(lk);
    cv.wait(lk, []{return i == 1;});
    for (int t=10; t!=0; t--)
    {
        std::cerr << id << " finish waiting " << t <<" seconds... \n";
        std::this_thread::sleep_for(std::chrono::seconds(1));
    }
}
 
void signals()
{
//    std::this_thread::sleep_for(std::chrono::seconds(1));
    {
        std::lock_guard<std::mutex> lk(cv_m);
        std::cerr << "Notifying...\n";
    }
//    cv.notify_all();
 
//    std::this_thread::sleep_for(std::chrono::seconds(1));
 
    {
        std::lock_guard<std::mutex> lk(cv_m);
        i = 1;
        std::cerr << "Notifying again...\n";
    }
//    cv.notify_one();
}
 
int main()
{
    std::thread t1(waits, 0), t2(waits, 1), t3(waits, 2), t4(signals);
    t1.join(); 
    t2.join(); 
    t3.join();
    t4.join();
}

Interestingly without predicate calling just cv.wait(lk); in waits causes infinite waiting. So it seems when the predicate is satisfied, no waiting occurs? See https://onlinegdb.com/Sr4iaHu5T So is there some magic going on or this is expected? The consequence is that cv.wait(lk, []{return true;}); causes no waiting and is not equivalent to cv.wait(lk);.

Is this something I can rely on? I mean I could call cond_var.wait(lock, []() { return !packet_queue.empty(); }); and know that if the queue isn't empty it won't wait even without notification.

VojtaK
  • 483
  • 4
  • 13
  • 2
    Side note: Be aware of [spurious wakeup](https://en.wikipedia.org/wiki/Spurious_wakeup)s - they are a real thing and *do* happen on some platform / tool-chain combinations. – Jesper Juhl Feb 28 '23 at 11:14
  • Also actual waiting is done after condition is checked and not met. – Marek R Feb 28 '23 at 11:20
  • If you remove/reduce sleep in `waits` and make sleep longer in `signal` then app freezes as expected, since `cv.wait(lk, []{return i == 1;});` will be reached before `i` is changed to meet condition. – Marek R Feb 28 '23 at 11:25
  • 1
    See also [std::condition_variable::wait with predicate](https://stackoverflow.com/q/33692574) – JaMiT Feb 28 '23 at 11:28

0 Answers0