Home

GMainContext

GMainContext is a core concept in GLib that represents a set of event sources (GSource objects) to be dispatched by a main loop. It provides the mechanism GLib uses for event-driven programming and for coordinating work across threads. A main loop runs within a GMainContext, processing ready sources by invoking their callbacks.

Contexts are thread-aware. Each thread can have its own thread-default GMainContext, and multiple contexts can be

A GMainLoop is associated with a GMainContext. When you create a loop with g_main_loop_new, you provide the

In practice, GMainContext underpins GTK, GNOME apps, and many network services. It enables flexible, thread-aware event

created
with
g_main_context_new
for
private
use.
Context
ownership
is
controllable
via
g_main_context_acquire
and
g_main_context_release,
which
determine
which
thread
may
dispatch
sources
for
a
given
context.
GMainContext
objects
are
reference-counted,
so
they
can
be
shared
and
kept
alive
across
different
parts
of
an
application
using
g_main_context_ref
and
g_main_context_unref.
context
to
use;
g_main_loop_run
starts
processing
sources
in
that
context,
and
g_main_context_dispatch
executes
ready
callbacks.
Functions
like
g_main_context_pending
help
check
for
pending
sources,
while
g_main_context_invoke
schedules
a
function
to
run
in
the
context’s
thread.
Additionally,
sources
can
be
attached
to
a
specific
context,
allowing
inter-thread
signaling
and
coordinated
scheduling
across
contexts.
handling
by
isolating
work
in
separate
contexts
while
still
permitting
cross-context
callbacks
and
synchronization
when
needed.