Can scoped_lock lock a shared_mutex in read mode?

Can scoped_lock lock a shared_mutex in read mode?

C++17 introduced both&nbsp;<code>std::shared_mutex</code>&nbsp;and&nbsp;<code>std::scoped_lock</code>. My problem is now, that it seems, that&nbsp;<code>scoped_lock</code>&nbsp;will lock a shared mutex always in exclusive (writer) mode, when it is passed as an argument, and not in shared (reader) mode. In my app, I need to update an object&nbsp;<code>dst</code>with data from an object&nbsp;<code>src</code>. I want to lock&nbsp;<code>src</code>&nbsp;shared and&nbsp;<code>dst</code>&nbsp;exclusive. Unfortunately, this has the potential for deadlock, if a call to another update method with&nbsp;<code>src</code>&nbsp;and&nbsp;<code>dst</code>&nbsp;switched occurs at the same time. So I would like to use the fancy deadlock avoidance mechanisms of&nbsp;<code>std::scoped_lock</code>.

C++17 introduced both std::shared_mutex and std::scoped_lock. My problem is now, that it seems, that scoped_lock will lock a shared mutex always in exclusive (writer) mode, when it is passed as an argument, and not in shared (reader) mode. In my app, I need to update an object dstwith data from an object src. I want to lock src shared and dst exclusive. Unfortunately, this has the potential for deadlock, if a call to another update method with src and dst switched occurs at the same time. So I would like to use the fancy deadlock avoidance mechanisms of std::scoped_lock.

I could use scoped_lock to lock both src and dst in exclusive mode, but that unnecessarily strict lock has performance backdraws elsewhere. However, it seems, that it is possible to wrap src's shared_mutex into a std::shared_lock and use that with the scoped_lock: When the scoped_lockduring its locking action calls try_lock() on the shared_lock, the later will actually call try_shared_lock() on src's shared_mutex, and that's what I need.

So my code looks as simple as this:

struct data {
    mutable std::shared_mutex mutex;
    // actual data follows
};

void update(const data& src, data& dst) { std::shared_lock slock(src.mutex, std::defer_lock); std::scoped_lock lockall(slock, dst.mutex); // now can safely update dst with src??? }

Is it safe to use a (shared) lock guard like this inside another (deadlock avoidance) lock guard?

Angular 9 Tutorial: Learn to Build a CRUD Angular App Quickly

What's new in Bootstrap 5 and when Bootstrap 5 release date?

Brave, Chrome, Firefox, Opera or Edge: Which is Better and Faster?

How to Build Progressive Web Apps (PWA) using Angular 9

What is new features in Javascript ES2020 ECMAScript 2020

C/C++ vs. Rust: A developer’s perspective

In this post, you'll see the difference between Rust and C/C++ in a developer’s perspective

Variable Introduction in C#[Bangla]

LIKE | COMMENT | SHARE | SUBSCRIBE A variable is nothing but a name given to a storage area that our programs can manipulate. Each variable in C# has a speci...