1. The Goal: Sharing Between Processes
By default, a read-write lock allocated in memory is valid only for threads within the same process.
- The Problem: If you fork a process or map a region of shared memory, you might want a Reader-Writer lock that resides in that shared memory to coordinate the parent and child (or unrelated processes).
- The Solution: You must explicitly set the Process Shared attribute.
2. The Setup Sequence
Just like with mutexes, you cannot simply assign a value to change this behavior. You must use an attribute object. The Functions:
pthread_rwlockattr_init: Initializes the attribute object.pthread_rwlockattr_setpshared: Sets the scope toPTHREAD_PROCESS_SHARED.pthread_rwlock_init: Initializes the actual lock using the attribute.pthread_rwlockattr_destroy: Cleans up the attribute object.
3. Code Example
Here is how you would initialize a read-write lock that resides in shared memory so that multiple processes can use it:
// 1. Declare variables
pthread_rwlockattr_t attr;
pthread_rwlock_t *rwlock_ptr;
// Assume 'rwlock_ptr' points to a region of Shared Memory...
// 2. Initialize the attribute
pthread_rwlockattr_init(&attr);
// 3. SET THE SHARING ATTRIBUTE
// PTHREAD_PROCESS_SHARED allows any process with access to the memory
// to use this lock. (Default is PTHREAD_PROCESS_PRIVATE)
pthread_rwlockattr_setpshared(&attr, PTHREAD_PROCESS_SHARED);
// 4. Initialize the lock using these attributes
pthread_rwlock_init(rwlock_ptr, &attr);
// 5. Clean up the attribute (no longer needed after init)
pthread_rwlockattr_destroy(&attr);4. Important Note on cleanup
Just like mutexes, if a process crashes while holding a read-write lock in shared memory, the system does not automatically release it. The lock stays held, likely causing other processes to hang (deadlock). Robustness in IPC is a major topic, and often System V Semaphores (Chapter 11) are preferred if automatic cleanup is strictly required.