I have some questions regarding read-write locks in POSIX Pthreads on a *nix system, say Linux for example.
I wish to know what is the default bias for read write lo
This does indeed depend on the implementation - so since you have asked about Linux specifically, my comments are refer to the current NPTL implementation of pthreads, which is used in modern glibc.
There are two related, but separate, issues here. Firstly, there is this situation:
The default action here is to allow the reader to proceed - effectively "jumping the queue" over the writer. You can, however, override this. If you use the pthread_rwlockattr_setkind_np()
function to set the PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP
flag on the attr
that you pass to pthread_rwlock_init()
, then your rwlock will block the reader in the above situation.
The second situation is:
In this situation, NPTL will always wake up a writer in preference to a reader.
Taken together, the above means that if you use the PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP
flag, your writers shouldn't be starved (of course, now a continuous stream of writers can starve the readers. C'est la vie). You can confirm all this by checking the sources (it's all very readable1) in pthread_rwlock_rdlock.c and pthread_rwlock_unlock.c.
Note that there is also a PTHREAD_RWLOCK_PREFER_WRITER_NP
, but it appears not to have the right effect - quite possibly a bug (or possibly not - see comment by jilles below).