Reader/writer locks

More formally known as Multiple readers, single writer locks, these locks are used when the access pattern for a data structure consists of many threads reading the data, and (at most) one thread writing the data. These locks are more expensive than mutexes, but can be useful for this data access pattern.

This lock works by allowing all the threads that request a read-access lock ( pthread_rwlock_rdlock() ) to succeed in their request. But when a thread wishing to write asks for the lock ( pthread_rwlock_wrlock() ), the request is denied until all the current reading threads release their reading locks ( pthread_rwlock_unlock() ).

Multiple writing threads can queue (in priority order) waiting for their chance to write the protected data structure, and all the blocked writer-threads will get to run before reading threads are allowed access again. The priorities of the reading threads are not considered.

There are also calls ( pthread_rwlock_tryrdlock() and pthread_rwlock_trywrlock() ) to allow a thread to test the attempt to achieve the requested lock, without blocking. These calls return with a successful lock or a status indicating that the lock couldn't be granted immediately.

Reader/writer locks aren't implemented directly within the kernel, but are instead built from the mutex and condvar services provided by the kernel.