Multithreaded Programming Guide

Destroy Read-Write Lock State

rwlock_destroy(3T)

#include <synch.h>  (or #include <thread.h>)

int rwlock_destroy(rwlock_t *rwlp);

Use rwlock_destroy(3T) to destroy any state associated with the read-write lock pointed to by rlwp. The space for storing the read-write lock is not freed. (For POSIX threads, see "pthread_rwlock_destroy(3T)".)

Return Values

rwlock_destroy() returns zero after completing successfully. Any other returned value indicates that an error occurred. When any of the following conditions occur, the function fails and returns the corresponding value.


EINVAL

Invalid argument.


EFAULT

rwlp points to an illegal address.

Read-Write Lock Example

Example 9-1 uses a bank account to demonstrate read-write locks. While the program could allow multiple threads to have concurrent read-only access to the account balance, only a single writer is allowed. Note that the get_balance() function needs the lock to ensure that the addition of the checking and saving balances occurs atomically.


Example 9-1 Read-Write Bank Account

rwlock_t account_lock;
float checking_balance = 100.0;
float saving_balance = 100.0;
...
rwlock_init(&account_lock, 0, NULL);
...

float
get_balance() {
    float bal;

    rw_rdlock(&account_lock);
    bal = checking_balance + saving_balance;									
    rw_unlock(&account_lock);
    return(bal);
}

void
transfer_checking_to_savings(float amount) {
    rw_wrlock(&account_lock);
    checking_balance = checking_balance - amount;
    saving_balance = saving_balance + amount;
    rw_unlock(&account_lock);
}