On coming across #include <condition_variable>

Sep 24, 2022 at 3:22am
Reading

#include <condition_variable>

on analyzing one's project code

what is it all about without yet get into very detail breakdown ?
Last edited on Sep 24, 2022 at 3:36am
Sep 24, 2022 at 3:25am
What it is all about is you need to do your own research and learning instead of expecting others to do it all for you.

Here's a bit of a nudge in the right direction, since you refuse to look for yourself:

https://en.cppreference.com/w/cpp/thread/condition_variable
Sep 24, 2022 at 12:43pm
Conditional variables are used in multi-threaded applications to "synchronize" threads.

Simply put, one or more threads can wait (block) on a conditional variable. When another threads signals (notifies) that conditional variable, then either all or just one of the "waiting" threads will be unblocked and allowed to go on...

As an aside: Unlike semaphores, a conditional variable does not have a "counter" associated with it. So, if you signal a conditional variable while no thread is currently waiting on that conditional variable, then the signal is simply "lost" (discarded).
Last edited on Sep 24, 2022 at 12:48pm
Sep 24, 2022 at 1:42pm
The condition_variable class is a synchronization primitive that can be used to block a thread, or multiple threads at the same time, until another thread both modifies a shared variable (the condition), and notifies the condition_variable. A condition variable is an object able to block the calling thread until notified to resume ++

https://en.cppreference.com/w/cpp/thread/condition_variable
https://cplusplus.com/reference/condition_variable/condition_variable

A simple example :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <condition_variable>
#include <iostream>
#include <future>
#include <vector>
#include <mutex>
#include <conio.h>
#include <chrono> // to wait

int main()
{
    std::vector<std::future<void>> v;
    std::mutex m;
    std::condition_variable cv; // condition variable

    for (int i = 0; i < 5; ++i)
        v.push_back(std::async([&](int n) { std::unique_lock<std::mutex> mx{ m }; cv.wait(mx); std::cout << "Thread " << n << std::endl; }, i + 1));
    // threads have been created but waiting the signal                           ^^^^^^^^^^^
    std::cout << "Now you get 5 threads waiting the main signal - the condition_variable" << std::endl;
    std::cout << "Press a key to proceed ..." << std::endl;
    char c;
    c = _getch();
    // notify the signal to all thread using the condition variable
    cv.notify_all();
    // or something else, but you HAVE to wait because of output
    std::this_thread::sleep_for(std::chrono::milliseconds(100));
    return 0;
}



Now you get 5 threads waiting the main signal - the condition_variable
Thread 4
Thread 3
Thread 1
Thread 5
Thread 2
Last edited on Sep 24, 2022 at 3:15pm
Topic archived. No new replies allowed.