In
computer science
Computer science is the study of computation, information, and automation. Computer science spans Theoretical computer science, theoretical disciplines (such as algorithms, theory of computation, and information theory) to Applied science, ...
, a readers–writer (single-writer lock,
a multi-reader lock, a push lock, or an MRSW lock) is a
synchronization
Synchronization is the coordination of events to operate a system in unison. For example, the Conductor (music), conductor of an orchestra keeps the orchestra synchronized or ''in time''. Systems that operate with all parts in synchrony are sa ...
primitive that solves one of the
readers–writers problems. An RW lock allows
concurrent access for read-only operations, whereas write operations require exclusive access. This means that multiple threads can read the data in parallel but an exclusive
lock
Lock(s) or Locked may refer to:
Common meanings
*Lock and key, a mechanical device used to secure items of importance
*Lock (water navigation), a device for boats to transit between different levels of water, as in a canal
Arts and entertainme ...
is needed for writing or modifying data. When a writer is writing the data, all other writers and readers will be blocked until the writer is finished writing. A common use might be to control access to a data structure in memory that cannot be updated
atomically and is invalid (and should not be read by another thread) until the update is complete.
Readers–writer locks are usually constructed on top of
mutexes and
condition variables, or on top of
semaphores.
Upgradable RW lock
Some RW locks allow the lock to be atomically upgraded from being locked in read-mode to write-mode, as well as being downgraded from write-mode to read-mode
Upgrading a lock from read-mode to write-mode is prone to deadlocks, since whenever two threads holding reader locks both attempt to upgrade to writer locks, a deadlock is created that can only be broken by one of the threads releasing its reader lock. The deadlock can be avoided by allowing only one thread to acquire the lock in "read-mode with intent to upgrade to write" while there are no threads in write mode and possibly non-zero threads in read-mode.
Priority policies
RW locks can be designed with different priority policies for reader vs. writer access. The lock can either be designed to always give priority to readers (''read-preferring''), to always give priority to writers (''write-preferring'') or be ''unspecified'' with regards to priority. These policies lead to different tradeoffs with regards to
Concurrency (computer science), concurrency and
starvation
Starvation is a severe deficiency in caloric energy intake, below the level needed to maintain an organism's life. It is the most extreme form of malnutrition. In humans, prolonged starvation can cause permanent organ damage and eventually, de ...
.
* ''Read-preferring RW locks'' allow for maximum concurrency, but can lead to write-starvation if contention is high. This is because writer threads will not be able to acquire the lock as long as at least one reading thread holds it. Since multiple reader threads may hold the lock at once, this means that a writer thread may continue waiting for the lock while new reader threads are able to acquire the lock, even to the point where the writer may still be waiting after all of the readers which were holding the lock when it first attempted to acquire it have released the lock. Priority to readers may be ''weak'', as just described, or ''strong'', meaning that whenever a writer releases the lock, any blocking readers always acquire it next.
* ''Write-preferring RW locks'' avoid the problem of writer starvation by preventing any ''new'' readers from acquiring the lock if there is a writer queued and waiting for the lock; the writer will acquire the lock as soon as all readers which were already holding the lock have completed. The downside is that write-preferring locks allows for less concurrency in the presence of writer threads, compared to read-preferring RW locks. Also the lock is less performant because each operation, taking or releasing the lock for either read or write, is more complex, internally requiring taking and releasing two mutexes instead of one. This variation is sometimes also known as "write-biased" readers–writer lock.
[ Java readers–writer lock implementation offers a "fair" mode]
* ''Unspecified priority RW locks'' does not provide any guarantees with regards read vs. write access. Unspecified priority can in some situations be preferable if it allows for a more efficient implementation.
Implementation
Several implementation strategies for readers–writer locks exist, reducing them to synchronization primitives that are assumed to pre-exist.
Using two mutexes
Raynal demonstrates how to implement an R/W lock using two mutexes and a single integer counter. The counter, , tracks the number of blocking readers. One mutex, , protects and is only used by readers; the other, (for "global") ensures mutual exclusion of writers. This requires that a mutex acquired by one thread can be released by another. The following is
pseudocode
In computer science, pseudocode is a description of the steps in an algorithm using a mix of conventions of programming languages (like assignment operator, conditional operator, loop) with informal, usually self-explanatory, notation of actio ...
for the operations:
Initialize
* Set to .
* is unlocked.
* is unlocked.
Begin Read
* Lock .
* Increment .
* If , lock .
* Unlock .
End Read
* Lock .
* Decrement .
* If , unlock .
* Unlock .
Begin Write
* Lock .
End Write
* Unlock .
This implementation is read-preferring.
Using a condition variable and a mutex
Alternatively an RW lock can be implemented in terms of a
condition variable, , an ordinary (mutex) lock, , and various counters and flags describing the threads that are currently active or waiting.
For a write-preferring RW lock one can use two integer counters and one Boolean flag:
* : the number of readers that have acquired the lock (integer)
* : the number of writers waiting for access (integer)
* : whether a writer has acquired the lock (Boolean).
Initially and are zero and is false.
The lock and release operations can be implemented as
Begin Read
* Lock
* While or :
** wait ,
* Increment
* Unlock .
End Read
* Lock
* Decrement
* If :
** Notify (broadcast)
* Unlock .
Begin Write
* Lock
* Increment
* While or is :
** wait ,
* Decrement
* Set to
* Unlock .
End Write
* Lock
* Set to
* Notify (broadcast)
* Unlock .
Programming language support
*
POSIX
The Portable Operating System Interface (POSIX; ) is a family of standards specified by the IEEE Computer Society for maintaining compatibility between operating systems. POSIX defines application programming interfaces (APIs), along with comm ...
standard
pthread_rwlock_t
and associated operations
* ReadWriteLock interface and the ReentrantReadWriteLock
locks in
Java
Java is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea (a part of Pacific Ocean) to the north. With a population of 156.9 million people (including Madura) in mid 2024, proje ...
version 5 or above
* Microsoft
System.Threading.ReaderWriterLockSlim
lock for
C# and other
.NET
The .NET platform (pronounced as "''dot net"'') is a free and open-source, managed code, managed computer software framework for Microsoft Windows, Windows, Linux, and macOS operating systems. The project is mainly developed by Microsoft emplo ...
languages
*
std::shared_mutex
read/write lock in
C++17
C17, C-17 or C.17 may refer to:
Transportation
* , a 1917 British C-class submarine
Air
* Boeing C-17 Globemaster III, a military transport aircraft
* Lockheed Y1C-17 Vega, a six-passenger monoplane
* Cierva C.17, a 1928 English experimental ...
*
boost::shared_mutex
and
boost::upgrade_mutex
locks in
Boost C++ Libraries
Boost, boosted or boosting may refer to:
Science, technology and mathematics
* Boost, positive manifold pressure in turbocharged engines
* Boost (C++ libraries), a set of free peer-reviewed portable C++ libraries
* Boost (material), a material b ...
*
SRWLock
, added to the
Windows
Windows is a Product lining, product line of Proprietary software, proprietary graphical user interface, graphical operating systems developed and marketed by Microsoft. It is grouped into families and subfamilies that cater to particular sec ...
operating system API as of
Windows Vista
Windows Vista is a major release of the Windows NT operating system developed by Microsoft. It was the direct successor to Windows XP, released five years earlier, which was then the longest time span between successive releases of Microsoft W ...
.
*
sync.RWMutex
in
Go
* Phase fair reader–writer lock, which alternates between readers and writers
*
std::sync::RwLock
read/write lock in
Rust
Rust is an iron oxide, a usually reddish-brown oxide formed by the reaction of iron and oxygen in the catalytic presence of water or air moisture. Rust consists of hydrous iron(III) oxides (Fe2O3·nH2O) and iron(III) oxide-hydroxide (FeO(OH) ...
* Poco::RWLock in
POCO C++ Libraries
In software engineering
Software engineering is a branch of both computer science and engineering focused on designing, developing, testing, and maintaining Application software, software applications. It involves applying engineering design pr ...
*
mse::recursive_shared_timed_mutex
in the
/github.com/duneroadrunner/SaferCPlusPlus SaferCPlusPluslibrary is a version o
std::shared_timed_mutex
that supports the recursive ownership semantics o
std::recursive_mutex
*
txrwlock.ReadersWriterDeferredLock
Readers/Writer Lock for
Twisted
*
rw_semaphore
in the
Linux kernel
The Linux kernel is a Free and open-source software, free and open source Unix-like kernel (operating system), kernel that is used in many computer systems worldwide. The kernel was created by Linus Torvalds in 1991 and was soon adopted as the k ...
[
]
Example in Rust
use std::sync::RwLock;
let lock = RwLock::new(5);
// many reader locks can be held at once
// read locks are dropped at this point
// only one write lock may be held, however
// write lock is dropped here
Alternatives
The
read-copy-update (RCU) algorithm is one solution to the readers–writers problem. RCU is
wait-free for readers. The
Linux kernel
The Linux kernel is a Free and open-source software, free and open source Unix-like kernel (operating system), kernel that is used in many computer systems worldwide. The kernel was created by Linus Torvalds in 1991 and was soon adopted as the k ...
implements a special solution for few writers called
seqlock.
See also
*
Semaphore (programming)
*
Mutual exclusion
In computer science, mutual exclusion is a property of concurrency control, which is instituted for the purpose of preventing race conditions. It is the requirement that one thread of execution never enters a critical section while a concurr ...
*
Scheduler pattern
*
Balking pattern
*
File locking
File locking is a mechanism that restricts access to a computer file, or to a region of a file, by allowing only one user or process to modify or delete it at a specific time, and preventing reading of the file while it's being modified or delet ...
*
Lock (computer science)
In computer science, a lock or mutex (from mutual exclusion) is a synchronization primitive that prevents state from being modified or accessed by multiple threads of execution at once. Locks enforce mutual exclusion concurrency control policies ...
*
Readers–writers problem
Notes
References
{{DEFAULTSORT:Readers-writer lock
Concurrency control
Software design patterns