Home

GMutex

GMutex is a mutual exclusion primitive provided by GLib to synchronize access to shared data in multi-threaded programs. It is part of GLib's threading facilities and abstracts platform-specific synchronization primitives, such as pthread mutexes on POSIX systems and CRITICAL_SECTION on Windows, to offer a portable interface for locking critical sections.

A GMutex is created with g_mutex_new() and must be freed with g_mutex_free() when it is no longer

Core operations include g_mutex_lock, g_mutex_unlock, and g_mutex_trylock. The g_mutex_lock function blocks the calling thread until the

GMutex is non-recursive by design; if the same thread attempts to lock it again while already holding

For static or global data, GLib also offers static mutex capabilities (such as GStaticMutex) to enable safe

In summary, GMutex provides a portable, non-recursive mutex API for protecting critical sections, with a simple

needed.
The
typical
pattern
is
to
create
a
mutex
once
and
reuse
it
to
protect
accesses
to
shared
resources.
mutex
becomes
available
and
then
acquires
the
lock.
The
g_mutex_unlock
function
releases
the
lock.
The
g_mutex_trylock
function
attempts
to
acquire
the
lock
without
blocking
and
returns
a
gboolean
indicating
success;
if
the
lock
is
not
available,
it
returns
FALSE.
the
lock,
a
deadlock
can
occur.
For
scenarios
requiring
recursive
locking,
GLib
provides
a
separate
primitive
called
GRecMutex.
initialization
without
explicit
dynamic
allocation.
GMutex
is
widely
used
within
GLib
and
GTK
code
to
protect
data
structures,
global
state,
and
other
resources
that
must
not
be
concurrently
modified.
lifecycle
and
predictable
blocking
semantics
suitable
for
cross-platform
GLib-based
applications.