Reader/writer locks

QNX SDP8.0System ArchitectureDeveloperUser

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 at a particular point in time. Although these locks do not support any form of priority inheritance or priority inversion avoidance, they are useful for this data access pattern.

Reader/writer locks work best in the case of frequent reads from multiple threads and very infrequent writes. If data updates are common enough, then the drawbacks of these locks—additional kernel calls, lack of explicit ownership and priority inheritance—make them perform poorly relative to mutexes.

These locks work by allowing multiple threads that request a shared (read) lock (pthread_rwlock_rdlock()) to succeed in their request as long as there is no exclusive (write) lock. But when a thread asks for an exclusive lock (pthread_rwlock_wrlock()), the request is denied until there is no current lock, meaning the writing thread and all reading threads have released their locks (pthread_rwlock_unlock()).

Multiple threads can queue (in priority order) while waiting for their chance to acquire the lock. When the lock is released, if the highest priority waiting thread is waiting for a shared lock, then a shared lock is granted to this thread and to any others that are waiting for this type of lock and have higher priority than the highest-priority thread that is waiting for an exclusive lock.

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

Page updated: