Showing posts with label cpp17_mutex. Show all posts
Showing posts with label cpp17_mutex. Show all posts

Mar 27, 2024

[C++] compare_exchange_weak / compare_exchange_strong and why spuriously fail happens

reference:
compare_exchange_weak / compare_exchange_strong

compare_exchange_strong; no spuriously fail


compare_exchange_weak; spuriously fail due to using timed lock; compare_exchange_weak is useful inside a loop;


A timed lock in C++ is a synchronization primitive, specifically a type of mutex, that allows a thread to attempt to acquire a lock for a specific maximum amount of time.

This is different from a standard std::mutex, where a thread calling lock() will block indefinitely until the mutex becomes available. A timed lock prevents a thread from getting stuck forever if another thread holds the lock and never releases it (due to a bug, for example).

In C++, the timed lock feature is provided by the std::timed_mutex class (and std::recursive_timed_mutex).

Aug 3, 2021

[C++] note about std::shared_mutex and pthread_rwlock_t

Reference:
std::shared_mutex
pthread_rwlock_init
stackoverflow response:
https://stackoverflow.com/a/57709957
https://stackoverflow.com/a/2190271


Take away:

C++17's std::shared_mutex on linux might using pthread_rwlock_t underneath, thus in order to tweak

the behavior of write starvation, set PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP in the pthread_rwlock_init call's pthread_rwlockattr_t is necessary.

For those not using pthread_rwlock_t, std::shared_mutex should rely on linux kernel's scheduler, which is fair, avoid either write/read starvation.


Here's how Go handles stavation:

http://vsdmars.blogspot.com/2021/03/go-methods-for-lock-starvation-barging.html