lundi 10 juillet 2023

Doesn't multiple std::lock_guard guarantee the order of locks?

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);    
  1. I thought the consistent ordering (lock lk1 first, and then lock lk2) across the different threads is enough to avoid deadlock, but why do we need std::lock(e1.m, e2.m)?
    (I also read other questions such as this but still not sure why just locking with multiple std::lock_guards are not enough even though they're locking in the same order.)

  2. Is this related to the fact that std::lock_guard supports RAII style?

Aucun commentaire:

Enregistrer un commentaire