How to prevent writer starvation in a read write lock in pthreads

拈花ヽ惹草 提交于 2019-11-27 03:18:51

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:

  • There are read locks currently held, and writers waiting. A new thread tries to take a read lock.

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:

  • The last holder releases the lock, and there are both readers and writers waiting.

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).


1. ...or at least it was, back when I wrote this answer in 2010. The latest versions of NPTL are considerably more complex and I haven't re-done the analysis.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!