vendredi 25 septembre 2015

Understanding std::condition_variables

I'm trying to understand the flow of the condition_variable when I have more than one thread waiting to execute. To my understanding, all threads would try to grab the unique lock, one would get it and then progress to the wait(), if you call notify_all, wouldn't there at most be one thread waiting that would be allowed through. Until it releases it's lock and allows the other threads through.

Does the cv communicate with the unique lock and let all threads through all at once? If so is it truly all at once or do the threads sequentially pass through one after another.

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()
{
    std::unique_lock<std::mutex> lk(cv_m);
    std::cerr << "Waiting... \n";
    cv.wait(lk, []{return i == 1;});
    std::cerr << "...finished waiting. i == 1\n";
}

http://ift.tt/1LBr8hW

Aucun commentaire:

Enregistrer un commentaire