Home

pthreadcleanuppushpthreadcleanuppop

pthread_cleanup_push and pthread_cleanup_pop are a pair of macros from the POSIX threads (pthreads) API used to manage per-thread cleanup handlers. They provide a structured way to ensure resources are released when a thread exits a region or is canceled.

Mechanics and semantics

When you call pthread_cleanup_push(func, arg), you register a cleanup handler consisting of a function pointer and

Usage pattern

The push and pop macros must appear as a matched pair within the same lexical scope. They

Notes

- The cleanup handlers run automatically upon thread cancellation or when the region is unwound, ensuring robust

- They are a C-language mechanism and are invoked in a portable way across POSIX-compliant systems; alternatives

See also

pthread_cancel, pthread_exit, cancellation points.

an
argument
on
a
per-thread
stack.
This
handler
will
be
invoked
if
the
thread
exits
the
scope
of
the
block
or
is
canceled
while
the
handler
remains
on
the
stack.
The
corresponding
pthread_cleanup_pop(execute)
removes
the
most
recently
pushed
handler
from
the
stack.
If
execute
is
nonzero,
the
handler
is
executed
immediately
at
the
point
of
the
pop
(provided
it
has
not
already
been
invoked
due
to
cancellation
or
unwinding).
Cleanup
handlers
are
executed
in
reverse
order
of
registration
when
the
thread
exits
the
region
or
is
canceled.
are
typically
used
to
guard
resources
such
as
dynamically
allocated
memory,
locks,
or
file
descriptors.
A
common
pattern
is
to
push
a
cleanup
handler
before
acquiring
a
resource,
perform
work,
and
then
pop
the
handler
with
execute
set
to
0
if
normal
completion,
or
with
execute
set
to
1
if
an
error
path
requires
immediate
cleanup.
resource
release.
exist
in
C++
(RAII)
or
careful
lock
management.