mercredi 18 septembre 2019

Does wait_until work differently in main thread wrt not main one? c++

Executing the same code in main thread wrt a separate one,the condition variable behaves differently

#include <iostream>
#include <condition_variable>
#include <mutex>
#include <chrono>
#include <thread>
using namespace std;
using namespace std::chrono;
using namespace std::chrono_literals;
void waits()
{
    std::mutex mCvMtx;
    std::condition_variable mCondVar;

   auto now = std::chrono::system_clock::now();

    std::unique_lock<std::mutex> lk(mCvMtx);
    if(mCondVar.wait_until(lk, now+ 3*1000ms) ==  cv_status::timeout)
    {
        cout << "Fire";
    }
    else
    {
        cout << "Condition variable notified ";
    }
    now = std::chrono::system_clock::now();
}

int main()
{

     std::thread t1(waits);
     t1.join(); 

    return 0;
}

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

int main()
{
     std::mutex mCvMtx;
    std::condition_variable mCondVar;

   auto now = std::chrono::system_clock::now();

    std::unique_lock<std::mutex> lk(mCvMtx);
    if(mCondVar.wait_until(lk, now+ 3*1000ms) ==  cv_status::timeout)
    {
        cout << "Fire";
    }
    else
    {
        cout << "Condition variable notified ";
    }
    now = std::chrono::system_clock::now();

    return 0;
}

I cannot understand why in the first example the output results in "Fire" (so the cv was not notified and it waits the time I indicated) while in the second case where I execute the same code in the main thread, the output results in "Condition variable notified", without wait any seconds.

Do you have any explanantion? thanks

Aucun commentaire:

Enregistrer un commentaire