[ Previous ] [ Contents ] [ Index ] [ Next ]

Ns_InitializeRWLock

Overview

Initialize a read/write lock

Syntax

    int Ns_InitializeRWLock(
    Ns_RWLock *lock
    );

Description

Initialize a read/write lock for use. A lock ID is returned via the lock parameter, which can be used in the other read/write lock functions.

About Read/Write Locks

Read/write locks are a serialization mechanism for using data structures where multiple reads can happen simultaneously, but where writes must happen singly. For example, suppose you have a hash table that is heavily used but doesn't change very often. You'd like to have multiple threads be able to read from the table without blocking on each other, but when you need to update the table, you can do so safely without having to worry about other threads reading incorrect data.

The principal feature of read/write locks is the mechanism of which locks have priority and which locks must wait. Any number of read locks can be pending. If there's a write lock active, the read lock acquisition blocks until the write lock is released. Also, only one write lock can be in effect. If there are pending read locks active, the write lock acquisition blocks until all of the read locks drain. If a subsequent read lock acquisition attempt is made while a write lock is waiting to acquire, the write lock has priority.

Ns_RWLockInit is the preferred function for initializing a read/write lock.

Examples

    NS_RWLock lock;
    int GetData (int key)
    {
        /* acquire a read lock */
        Ns_ReadLockRWLock (&lock);
        search through the data structure looking for key's data;
        
        /* release our read lock */
        Ns_ReadUnlockRWLock (&lock);
        return (value);
       
    } /* GetData */
    int StoreData (int key, int value)
    {
       /* acquire the write lock */
       Ns_WriteLockRWLock (&lock);
       manipulate the data structure storing key's value;
       /* release the write lock */
       Ns_WriteUnlockRWLock (&lock);
       return (value);
    } /* StoreData */
    ...
    Ns_InitializeRWLock (&lock);
    ...
    (different threads using GetData and StoreData)
    ...
    Ns_DestoryRWLock (&lock);

See Also

Ns_DestroyRWLock

Ns_ReadLockRWLock

Ns_ReadUnlockRWLock

Ns_WriteLockRWLock

Ns_WriteUnlockRWLock

Top of Page

[ Previous ] [ Contents ] [ Index ] [ Next ]
Copyright © 1998-99 America Online, Inc.