Home

pthreadmutex

pthread_mutex is a POSIX threads synchronization primitive used to control access to shared data in multi-threaded programs. A mutex (mutual exclusion) allows only one thread at a time to execute a critical section protected by the mutex, preventing data races.

Usage: The mutex object can be statically initialized with PTHREAD_MUTEX_INITIALIZER or dynamically with pthread_mutex_init, which accepts

Mutex types and attributes: The type is defined by pthread_mutexattr_t. Standard types include PTHREAD_MUTEX_NORMAL, PTHREAD_MUTEX_ERRORCHECK, PTHREAD_MUTEX_RECURSIVE,

Notes: The mutex must be unlocked by the thread that holds it; unlocking by a non-owner yields

See also: pthread_spinlock, pthread_cond, pthread_rwlock.

a
mutex
attribute
object.
Operations
include
pthread_mutex_lock
to
acquire,
pthread_mutex_trylock
to
attempt
without
blocking,
pthread_mutex_unlock
to
release,
and
pthread_mutex_destroy
when
finished.
If
a
thread
attempts
to
lock
a
mutex
already
owned
by
another
thread,
behavior
depends
on
the
mutex
type;
blocking
lock
will
wait
until
ownership
is
released,
while
trylock
returns
EBUSY.
and
PTHREAD_MUTEX_DEFAULT.
Normal
type
may
lead
to
undefined
behavior
if
a
thread
attempts
to
relock
the
mutex
it
already
holds;
error-check
type
detects
such
errors
and
may
return
an
error;
recursive
type
allows
the
owning
thread
to
acquire
the
same
mutex
multiple
times
and
requires
the
same
number
of
unlocks.
The
default
type
is
implementation-defined
and
may
be
equivalent
to
one
of
the
others.
Additional
attributes
support
robustness
(PTHREAD_MUTEX_ROBUST)
and
priority
handling
(PTHREAD_PRIO_INHERIT,
PTHREAD_PRIO_PROTECT).
undefined
behavior
for
normal
and
error-checking
types,
while
robust
types
provide
recovery
semantics.
Deadlocks
can
occur
if
multiple
threads
hold
multiple
mutexes
in
conflicting
orders.