vendredi 14 juillet 2017

Why re-use of mutex of a condition variable will result in endless loop?

I confronted a code here when I was seeking for help of the implementation of std::condition_variable in C++ 11. In the question above, such code can be executed correctly whereas adding the comment line in function void g() results in deadlock occasionally. And I want to know why and the exactly inner mechanism of std::condition_variable::wait()(cpp reference really confuses me). Thanks in advance.

#include <thread>
#include <mutex>
#include <condition_variable>
#include <iostream>

std::mutex mtx;
std::condition_variable cv;

void f() {
    {
        std::unique_lock<std::mutex>  lock( mtx );
        cv.wait( lock );
    }
    std::cout << "f()\n";
}

void g() {
    // std::unique_lock<std::mutex>  lock( mtx ); adding this line will result in 
    //                                            deadlock.
    std::this_thread::sleep_for( std::chrono::seconds(1) );
    cv.notify_one();
}

int main() {
    for (int i = 1; i <= 100; i++) {
        std::cout << i << std::endl;
        std::thread  t1{ f };
        std::thread  t2{ g };
        t2.join();
        t1.join();
    }
}

Aucun commentaire:

Enregistrer un commentaire