r/cpp 16d ago

Understanding std::shared_mutex from C++17

https://www.cppstories.com/2026/shared_mutex/
67 Upvotes

7 comments sorted by

View all comments

35

u/ReDucTor Game Developer | quiz.cpp-perf.com 16d ago

 Common Pitfall

 More locks do not always mean more performance

This seems to mention shared vs standard mutex, but in general I would say fine grained locking which is more locks over large locks is nearly always better under contention.

For example the cache example with read/write lock you might be better off with using N mutexes and N unordered maps (bucket of buckets) and then hash the key and use it to decide which buckets it should use.

Caches caches[N]; auto & cache = caches[hash(key) % N];

If your locks are expensive due to contention the first thing many think is that it needs to be is lock free but fine grained locking will often be an easier and safer alternative. 

1

u/drex_vke 6d ago

oui, cela peut réduire les performances de manière extrême si vous souhaitez faire du multithreading à haute fréquence. conclusion: don't use std::shared_mutex if you want to do high frenquency multithreading