mercredi 31 mai 2017

Several mutexes locking in c++

In many places there is a suggestion to use std::defer_lock:

{
    std::unique_lock<std::mutex> lk1(mutex1, std::defer_lock);
    std::unique_lock<std::mutex> lk2(mutex2, std::defer_lock);
    std::lock(lk1, lk2);
    //Do some stuff
}

But what if I won't use std::defer_lock, and try to do simply that:

{
    std::unique_lock<std::mutex> lk1(mutex1);
    std::unique_lock<std::mutex> lk2(mutex2);
    //Do some stuff
}

As far as I know, this code will lock mutex1, and then lock mutex2. Unlocking will be performed in the reverse order - mutex2, and then mutex1. There is no reason to deadlock.

Documentation says, that std::lock(lk1, lk2); in the first example would lock buth mutexes simultaneously. So, is this some sort of optimization?

Aucun commentaire:

Enregistrer un commentaire