scoped_lock inside lock_guard, is it redundant?

83 views Asked by At

I'm new in multi-thread programming. I'm now doing a serial port communication project, and search related codes for reference. I found a code that someone used scoped_lock inside lock_guard as below:

void B(){
     boost::mutex::scoped_lock b_lock(b_mutex);
     /* do something */
}

void A(){
     const std::lock_guard<std::mutex> a_lock(a_mutex);
     /* do something  */
     B();
}

According to this post, I think these two are just to lock mutex. And B() is called by A(), so maybe scoped_lock inside B() is not needed, and can be removed. Is it right?

1

There are 1 answers

1
463035818_is_not_an_ai On BEST ANSWER

They lock different mutexes. Whether this makes sense depends on what is do something. For example it could be:

void B(){
     boost::mutex::scoped_lock b_lock(b_mutex);
     /* do something that needs b_mutex locked */
}

void A(){
     const std::lock_guard<std::mutex> a_lock(a_mutex);
     /* do something that needs a_mutex locked  */
     B();
}

It seems like A could be changed to

void A(){
     { 
         const std::lock_guard<std::mutex> a_lock(a_mutex);
         /* do something that needs a_mutex locked  */
     }
     B();
}

But whether this is still correct depends on details that were left out from the posted code.

Locking two different mutexes is not redundant, because other threads may lock only one of them.