C++ Portable Types Library (PTypes) Version 1.7

Top: Multithreading: rwlock

#include <pasync.h>

void rwlock::rdlock();
void rwlock::wrlock();
void rwlock::unlock();

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.

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 will 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 will wait 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.

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

PTypes home