RyanChen.YLC
RyanChen.YLC

Reputation: 87

scoped_lock inside lock_guard, is it redundant?

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?

Upvotes: 0

Views: 124

Answers (1)

463035818_is_not_an_ai
463035818_is_not_an_ai

Reputation: 123253

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.

Upvotes: 3

Related Questions