If a thread is the owner of one or more shared read locks acquired by pthread_rwlock_unlock(), pthread_rwlock_tryrdlock(), or pthread_rwlock_timedrdlock_np(), when that thread terminates, the shared read locks are automatically released by the system. If a thread holds a shared read lock, it does not modify the resources associated with that lock. It is then safe for the runtime support to unlock the read lock without indicating an error condition or causing the process to wait. For performance reasons, your application should unlock all held locks before the thread ends.
If a thread is the owner of one or more exclusive write locks acquired by pthread_rwlock_wrlock(), pthread_rwlock_trywrlock(), or pthread_rwlock_timedwrlock_np(), when that thread terminates, the exclusive write locks are not automatically released by the system. This is an error in the application and indicates that the data associated with the lock is in an inconsistent state. If another thread attempts to get a shared read or exclusive write lock on the lock, that thread blocks forever.
The i5/OS implementation of read/write locks allows a thread to effectively change a read lock to a write lock, or change a write lock to a read lock, without an intervening unlocked and unprotected section of code. The following items describe read/write lock behavior that allows these changes. This behavior is outside of the definition of the Single UNIX Specification. An application written to be portable to the Single UNIX Specification should not attempt to acquire a shared read lock and a shared write lock on the same read/write lock at the same time.
For a thread to change a shared read lock to an exclusive write lock, the thread should perform the following actions:
{ pthread_rwlock_t rwlock = PTHREAD_RWLOCK_INITIALIZER; pthread_rwlock_rdlock(&rwlock); ... /* Thread holding a read lock decides it needs to upgrade to a write lock */ /* Now Upgrade to write lock */ pthread_rwlock_wrlock(&rwlock); ... /* write lock (and read lock) are held here.*/ /* We have effectively upgraded to a write lock */ ... /* `Downgrade' back to a only the read lock */ pthread_rwlock_unlock(&rwlock); ... /* unlock the read lock */ pthread_rwlock_unlock(&rwlock); }
For a thread to change an exclusive write lock to a shared read lock, the thread should perform the following actions:
{ pthread_rwlock_t rwlock = PTHREAD_RWLOCK_INITIALIZER; pthread_rwlock_wrlock(&rwlock); .. /* Thread holding the write lock decides it needs to downgrade to a read lock */ /* Get the read lock, so we are holding BOTH read and write locks */ pthread_rwlock_rdlock(&rwlock); ... /* An unlock always unlocks the write lock first */ pthread_wrlock_unlock(&rwlock); ... /* At this point, we are only holding the read lock. */ /* We have effectively downgraded the write lock to a read lock */ ... /* Use unlock to unlock the last read lock. */ pthread_wrlock_unlock(&rwlock); }
Top | Pthread APIs | APIs by category |