Multithreaded Programming Guide

Exit Print View

Updated: July 2014
 
 

Similar Synchronization Functions: Read-Write Locks

Read-write locks allow simultaneous read access by many threads while restricting write access to only one thread at a time. This section discusses the following topics:

  • Initializing a readers/writer lock

  • Acquiring a read lock

  • Trying to acquire a read lock

  • Acquiring a write lock

  • Trying to acquire a write

  • Unlocking a readers/writer lock

  • Destroying readers/writer lock state

When any thread holds the lock for reading, other threads can also acquire the lock for reading but must wait to acquire the lock for writing. If one thread holds the lock for writing, or is waiting to acquire the lock for writing, other threads must wait to acquire the lock for either reading or writing.

Read-write locks are slower than mutexes. But read-write locks can improve performance when the locks protect data not frequently written but are read by many concurrent threads.

Use read-write locks to synchronize threads in this process and other processes. Allocate read-write locks in memory that is writable and shared among the cooperating processes. See themmap(2) man page for information about mapping read-write locks for this behavior.

By default, the acquisition order is not defined when multiple threads are waiting for a read-write lock. However, to avoid writer starvation, the Oracle Solaris threads package tends to favor writers over readers of equal priority.

Read-write locks must be initialized before use.