logoalt Hacker News

Understanding Std:Shared_mutex from C++17

37 pointsby ibobevlast Tuesday at 4:43 PM22 commentsview on HN

Comments

stevefan1999today at 4:40 PM

The equivalent in Rust is RwLock: https://doc.rust-lang.org/std/sync/struct.RwLock.html

The more general idea for this is readers-writer lock: https://en.wikipedia.org/wiki/Readers%E2%80%93writer_lock

loegtoday at 3:19 PM

https://www.cppstories.com/2026/shared_mutex/#newer-concurre...

> Since C++17, the concurrency library has expanded significantly. We now have:

> ...

> safe memory reclamation mechanisms (RCU, hazard pointers in C++26)

> These tools focus mostly on thread lifetime, coordination, cancellation or lock-free programming.

> std::shared_mutex fills a different role.

> It is still a mutual-exclusion primitive, explicitly designed to protect a shared state with many readers and few writers. It does not compete with atomics, condition variables, or RCU.

What does it mean to say shared_mutex does not "compete" with atomics/CVs/RCU? There are many situations where RCU or other safe reclamation mechanism is a good replacement for state + shared_mutex. (And some situations where atomics are a decent replacement.)

show 1 reply
i_am_a_peasanttoday at 12:13 PM

You know it often is the case that APIs like this both in C++ and Rust don't offer you enough knobs when your usecase deviates from being trivial.

It happens with locking APIs, it happens with socket APIs, anything platform dependent.

Does the C++ standard give you an idiomatic way to set PTHREAD_RWLOCK_PREFER_READER_NP or PTHREAD_RWLOCK_PREFER_WRITER_NP explicitly when initializing a rwlock? Nope. Then you either roll your own or in Rust you reach for a crate where someone did the work of making a smarter primitive for you.

show 4 replies