samedi 23 juillet 2016

Why unique_lock call unlock, when he does not owning mutex?

In this example, std::unique_lock call with flag std::defer_lock. On cppreference written: "defer_lock_t do not acquire ownership of the mutex" and : "(destructor) unlocks the associated mutex, if owned "

And now, the question!

Why in this example, std::unique_lock calls unlock in destructors?

void transfer(Box &from, Box &to, int num)
{
    // don't actually take the locks yet
    std::unique_lock<std::mutex> lock1(from.m, std::defer_lock);
    std::unique_lock<std::mutex> lock2(to.m, std::defer_lock);

    // lock both unique_locks without deadlock
    std::lock(lock1, lock2);

    from.num_things -= num;
    to.num_things += num;

    // 'from.m' and 'to.m' mutexes unlocked in 'unique_lock' dtors
}

?????

Aucun commentaire:

Enregistrer un commentaire