Oct 13, 2021

[C++] std::shared_mutex

Reference:
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2406.html#shared_mutex_imp
https://stackoverflow.com/a/57709957


shared_mutex can certainly be implemented on top of an OS supplied read-write mutex. However a portable subset of the implementation is shown here for the purpose of motivating the existence of cond_var: the razor-thin layer over the OS condition variable.

A secondary motivation is to explain the lack of reader-writer priority policies in shared_mutex.

This is due to an algorithm credited to Alexander Terekhov which lets the OS decide which thread is the next to get the lock without caring whether a unique lock or shared lock is being sought. This results in a complete lack of reader or writer starvation. It is simply fair.


GCC on linux underneath using pthread_rwlock_t for the std::shared_lock implementation, to use kernel’s scheduler, there’s a header config:
_GLIBCXX_USE_PTHREAD_RWLOCK_T
to disable pthread_rwlock_t.

for pthread_rwlock_t,  by default it prefers read than write.

It can be config through:
PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.