0

I am trying to understand std::condition_variable in C++. I expect the wait statement in function called third to prevent progression until second and first have finished, but this isn't the case. Why isn't it waiting? It is consistently printing 1,3,2.

#include <functional>
#include <mutex>
#include <condition_variable>
#include <future>
#include <iostream>
#include <string>
condition_variable c;
bool is1C=false, is2C=false, is3C=false;
mutex m1,m2,m3;
void printFirst(){
    cout<<"1";
}
void printSecond(){
    cout<<"2";
}
void printThird(){
    cout<<"3";
}
void first(function<void()> printFirst) {
    printFirst();
    is1C=true;
    c.notify_all();
}

void second(function<void()> printSecond) {
    unique_lock<mutex> sL1(m1);
    c.wait(sL1,[]{return is1C==true;});
    printSecond();
    is2C=true;
    c.notify_all();
}

void third(function<void()> printThird) {
    unique_lock<mutex> sL2(m2);
    c.wait(sL2,[]{return is2C==true && is2C==true;});
    printThird();
}

int main() {
    function<void()> printFirstN=printFirst;
    function<void()> printSecondN=printSecond;
    function<void()> printThirdN=printThird;
    std::async(printFirstN);
    std::async(printThirdN);
    std::async(printSecondN);
}
Hisham Hijjawi
  • 1,803
  • 2
  • 17
  • 27
  • Why shouldn't it? The order in which the threads are run is not guaranteed. Also, shouldn't be the mutex also be shared among the threads? – Mario The Spoon Oct 23 '19 at 04:09
  • @NicolBolas I don't see the connection between that question and this one... – Hisham Hijjawi Oct 23 '19 at 04:16
  • @user3586940: From the second sentence of the accepted answer: "*You must have a mutex and it must guard a message of some kind for them to work*" Your mutex is not properly guarding anything; it's only being used at the cite where the condition variable is reading the data, not when it is being written. – Nicol Bolas Oct 23 '19 at 04:53
  • The code doesn't even call functions with CV... – toozyfuzzy Oct 23 '19 at 06:16

0 Answers0