Daily bit(e) of C++ | std::scoped_lock
Daily bit(e) of C++ ♻️31, The C++17 deadlock-free scoped lock for multiple mutexes: std::scoped_lock.
The C++17 std::scoped_lock is an RAII lock that provides a library-level solution for acquiring locks on multiple mutexes without risking a deadlock.
When locks are not always acquired in the same order, we can trivially introduce a situation in which thread T1 holds lock A and tries to acquire lock B while thread T2 holds lock B and tries to acquire lock A, resulting in a deadlock.
While the same logic can be achieved using std::lock, that approach requires the unlocking to be handled by the caller.