Locking multiple mutexes

后端 未结 3 1059
猫巷女王i
猫巷女王i 2020-12-16 12:31

I\'m wondering if it\'s possible to lock multiple mutexes at the same time, like:

 Mutex1.Lock();
 {
     Mutex2.Lock();
     {
          // Code locked by m         


        
3条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-16 13:05

    It is possible but the order of locking must be consistent throughout the application otherwise deadlock is a likely result (if two threads acquire the locks in opposite order then each thread could be waiting on the other to release one of the locks).

    Recommend using a scoped lock and unlock facility for exception safety, to ensure locks are always released (std::lock_guard with std::mutex for example):

    std::mutex mtx1;
    std::mutex mtx2;
    
    std::lock_guard mtx1_lock(mtx1);
    {
        std::lock_guard mtx2_lock(mtx2);
        {
        }
    }
    

    If your compiler does not support these C++11 features boost has similar in boost::mutex and boost::lock_guard.

提交回复
热议问题