Top: Multithreading: rwlock

>     #include <pasync.h>

>     class rwlock {
>         rwlock();
>         void rdlock();
>         void wrlock();
>         void unlock();
>     }

>     class scoperead {
>         scoperead(rwlock&);
>         ~scoperead();
>     }

>     class scopewrite {
>         scopewrite(rwlock&);
>         ~scopewrite();
>     }

Rwlock (read/write lock) is a variation of mutex with a possibility to control critical sections more efficiently. Unlike the simple mutex, rwlock allows multiple reader threads to enter the critical section, and only one writer thread at a time. Reading and writing in this context means access to a resource or compound data shared between threads. Reader threads must lock the critical section with rdlock() and the writers must lock it with wrlock(). Both leave the critical section with unlock().

This class incorporates POSIX rwlock interface on UNIX and library's own implementation on Windows and MacOS X. When using the rwlock class on Linux, you need to define a symbol _GNU_SOURCE either in the command line, or anywhere in your source before including any system headers.

Analogously to scopelock (see mutex), scoperead and scopewrite are fully-inline'd utility classes provided for exception-safe locking of operator blocks.

Please, see Portability and performance issues for additional notes on rwlock implementation.

rwlock::rwlock() creates a rwlock object.

void rwlock::rdlock() locks the object for reading. Multiple threads can enter the critical section through rdlock(), however, if the object is already locked for writing, all reader threads wait until the writer leaves the critical section.

void rwlock::wrlock() locks the object for writing. If there are readers inside the critical section, the writer waits until all threads leave and unlock the object. Only one writer at a time can enter the critical section.

void rwlock::unlock() unlocks the object. Both readers and writers must use this method when leaving the critical section.

scoperead::scoperead(rwlock& rw) creates a scoperead object and calls rdlock() for the object rw.

scoperead::~scoperead() calls unlock() for the rwlock object specified during construction and destroys the scoperead object.

scopewrite::scopewrite(rwlock& rw) creates a scopewrite object and calls wrlock() for the object rw.

scopewrite::~scopewrite() calls unlock() for the rwlock object specified during construction and destroys the scopewrite object.

See also: thread, mutex, trigger, semaphore, Examples

PTypes home