In the cppreference.com std::lock example, there is a code like this:
// use std::lock to acquire two locks without worrying about
// other calls to assign_lunch_partner deadlocking us
{
std::lock(e1.m, e2.m);
std::lock_guard<std::mutex> lk1(e1.m, std::adopt_lock);
std::lock_guard<std::mutex> lk2(e2.m, std::adopt_lock);
-
I thought the consistent ordering (lock
lk1first, and then locklk2) across the different threads is enough to avoid deadlock, but why do we needstd::lock(e1.m, e2.m)?
(I also read other questions such as this but still not sure why just locking with multiplestd::lock_guards are not enough even though they're locking in the same order.) -
Is this related to the fact that
std::lock_guardsupports RAII style?
Aucun commentaire:
Enregistrer un commentaire