Home

ReadWriteLock

ReadWriteLock is a synchronization primitive that allows multiple threads to acquire a shared lock for reading while ensuring that write operations have exclusive access. It supports a separation of concerns between readers and writers by providing two distinct locks: one for reading and one for writing. The lock is typically used to protect a shared resource with high-read, low-write access patterns.

If no thread holds the write lock, any number of reader threads can hold the read lock

In common programming libraries, the ReadWriteLock interface provides access to a readLock and a writeLock. The

Java's ReentrantReadWriteLock is a widely used example; C++ provides shared_mutex; pthreads provides pthread_rwlock_t. Depending on language

Read-write locks are appropriate when reads greatly outnumber writes and read operations can safely proceed concurrently.

concurrently.
When
a
thread
acquires
the
write
lock,
all
other
read
and
write
locks
are
blocked
until
the
writer
releases
the
lock.
Implementations
may
be
fair
or
non-fair,
affecting
whether
waiting
readers
or
writers
are
granted
access
in
a
first-in-first-out
order.
Some
implementations
may
prefer
writers
to
prevent
writer
starvation,
at
the
cost
of
reducing
read
parallelism.
locks
support
standard
operations
such
as
lock,
unlock,
and
tryLock,
with
optional
timeout
variants.
Reentrancy
and
memory
visibility
guarantees
depend
on
the
specific
implementation.
and
library,
features
such
as
reentrancy,
fairness,
and
upgrading
a
read
lock
to
a
write
lock
vary.
They
should
be
avoided
when
writes
are
frequent
or
when
the
overhead
of
managing
the
lock
outweighs
the
benefit
of
concurrency,
as
improper
use
can
lead
to
deadlocks
or
starvation.