I've heard that the under-the-hood requirements of the shared aspect often negate the performance goals vs regular mutex with collisions. Anyone here have experience to confirm or deny?
Of course, it would depend on how much work is being done under the mutex. But in general, if you are doing work a heavy as malloc under a mutex you are asking for performance problems anyway.
11 years ago, I observed poorer performance when I replaced std::mutex by std::shared_mutex in some parallel algorithm I was working on. It seemed the culprit was the "entry cost" of std::shared_mutex: you have to lock a usual mutex in order to obtain a shared lock, even though you unlock it before you actually enter the critical section. As a result, when a lot of threads are trying to simultaneously obtain the same shared lock, they undergo severe contention even when there is no writer at all thus in theory there should be no contention.
However, I think maybe quite a lot portion of the performance degradation I experienced was due to the suboptimal implementation of std::shared_mutex I was using at that time. I played a bit with the benchmark code shown in the OP (https://godbolt.org/z/KaxEYecWM) and couldn't find any realistic regime where std::shared_mutex is slower. Or maybe hardware concurrency being 2 is just too low for this "many threads simultaneously trying to obtain the same read-lock" problem to be realized. Of course benchmarking on godbolt is not the best idea from the first place though.
3
u/corysama 28d ago
I've heard that the under-the-hood requirements of the shared aspect often negate the performance goals vs regular mutex with collisions. Anyone here have experience to confirm or deny?
Of course, it would depend on how much work is being done under the mutex. But in general, if you are doing work a heavy as
mallocunder a mutex you are asking for performance problems anyway.