Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

boost::lock_guard vs boost::mutex::scoped_lock

Which is preferred boost::lock_guard or boost::mutex::scoped_lock?

I'm using Boost.Thread with the hope to move to C++11 threading when it becomes available.

Is scoped_lock part of the next c++ standard?

Are the any advantages to prefer one over the other?


NOTE: I'm aware that scoped_lock is just a typedef of lock_guard.


edit: I was wrong scoped_lock is not a typedef of lock_guard. It's a typedef of unique_lock.

like image 726
deft_code Avatar asked Feb 16 '10 22:02

deft_code


People also ask

Is lock_guard deprecated?

There exist valid use cases where it is desirable for scoped_lock to accept variadic template parameter packs which may be empty. And the empty case should not lock anything. And that's why lock_guard isn't deprecated.

What is the difference between unique_lock and lock_guard?

A lock_guard always holds a lock from its construction to its destruction. A unique_lock can be created without immediately locking, can unlock at any point in its existence, and can transfer ownership of the lock from one instance to another.

What is Scoped_lock?

The class scoped_lock is a mutex wrapper that provides a convenient RAII-style mechanism for owning one or more mutexes for the duration of a scoped block.


2 Answers

Amit is right: boost::mutex::scoped_lock is a typedef for boost::unique_lock<boost::mutex>, not lock_guard. scoped_lock is not available in C++0x.

Unless you need the flexibility of unique_lock, I would use lock_guard. It is simpler, and more clearly expresses the intent to limit the lock to a defined scope.

like image 140
Anthony Williams Avatar answered Sep 23 '22 11:09

Anthony Williams


Not much difference between the two. As per Boost, scoped_lock is a typedef for unique_lock<mutex>. Both of unique_lock and lock_guard implement RAII-style locking. The difference between is simply that unique_lock has a more complex interface -- it allows to defer lock and call unlock.

like image 26
amit kumar Avatar answered Sep 24 '22 11:09

amit kumar