C++17 introduced a new lock class called std::scoped_lock
.
Judging from the documentation it looks similar to the already existing std::lock_guard
class.
What's the difference and when should I use it?
The scoped_lock
is a strictly superior version of lock_guard
that locks an arbitrary number of mutexes all at once (using the same deadlock-avoidance algorithm as std::lock
). In new code, you should only ever use scoped_lock
.
The only reason lock_guard
still exists is for compatibility. It could not just be deleted, because it is used in current code. Moreover, it proved undesirable to change its definition (from unary to variadic), because that is also an observable, and hence breaking, change (but for somewhat technical reasons).