setcontext is one of a family of
C library
A library is a collection of Book, books, and possibly other Document, materials and Media (communication), media, that is accessible for use by its members and members of allied institutions. Libraries provide physical (hard copies) or electron ...
functions (the others being getcontext, makecontext and swapcontext) used for
context
In semiotics, linguistics, sociology and anthropology, context refers to those objects or entities which surround a ''focal event'', in these disciplines typically a communicative event, of some kind. Context is "a frame that surrounds the event ...
control. The
setcontext
family allows the implementation in C of advanced
control flow
In computer science, control flow (or flow of control) is the order in which individual statements, instructions or function calls of an imperative program are executed or evaluated. The emphasis on explicit control flow distinguishes an '' ...
pattern
A pattern is a regularity in the world, in human-made design, or in abstract ideas. As such, the elements of a pattern repeat in a predictable manner. A geometric pattern is a kind of pattern formed of geometric shapes and typically repeated l ...
s such as
iterator
In computer programming, an iterator is an object that progressively provides access to each item of a collection, in order.
A collection may provide multiple iterators via its interface that provide items in different orders, such as forwards ...
s,
fibers
Fiber (spelled fibre in British English; from ) is a natural or artificial substance that is significantly longer than it is wide. Fibers are often used in the manufacture of other materials. The strongest engineering materials often inco ...
, and
coroutine
Coroutines are computer program components that allow execution to be suspended and resumed, generalizing subroutines for cooperative multitasking. Coroutines are well-suited for implementing familiar program components such as cooperative task ...
s. They may be viewed as an advanced version of
setjmp/longjmp; whereas the latter allows only a single non-local jump up the
stack
Stack may refer to:
Places
* Stack Island, an island game reserve in Bass Strait, south-eastern Australia, in Tasmania’s Hunter Island Group
* Blue Stack Mountains, in Co. Donegal, Ireland
People
* Stack (surname) (including a list of people ...
,
setcontext
allows the creation of multiple
cooperative
A cooperative (also known as co-operative, coöperative, co-op, or coop) is "an autonomy, autonomous association of persons united voluntarily to meet their common economic, social and cultural needs and aspirations through a jointly owned a ...
threads of control, each with its own stack.
Specification
setcontext
was specified in
POSIX
The Portable Operating System Interface (POSIX; ) is a family of standards specified by the IEEE Computer Society for maintaining compatibility between operating systems. POSIX defines application programming interfaces (APIs), along with comm ...
.1-2001 and the
Single Unix Specification
The Single UNIX Specification (SUS) is a standard for computer operating systems, compliance with which is required to qualify for using the "UNIX" trademark. The standard specifies programming interfaces for the C language, a command-line shell, ...
, version 2, but not all
Unix-like
A Unix-like (sometimes referred to as UN*X, *nix or *NIX) operating system is one that behaves in a manner similar to a Unix system, although not necessarily conforming to or being certified to any version of the Single UNIX Specification. A Uni ...
operating system
An operating system (OS) is system software that manages computer hardware and software resources, and provides common daemon (computing), services for computer programs.
Time-sharing operating systems scheduler (computing), schedule tasks for ...
s provide them.
POSIX
The Portable Operating System Interface (POSIX; ) is a family of standards specified by the IEEE Computer Society for maintaining compatibility between operating systems. POSIX defines application programming interfaces (APIs), along with comm ...
.1-2004 obsoleted these functions,
and in
POSIX
The Portable Operating System Interface (POSIX; ) is a family of standards specified by the IEEE Computer Society for maintaining compatibility between operating systems. POSIX defines application programming interfaces (APIs), along with comm ...
.1-2008 they were removed, with
POSIX Threads indicated as a possible replacement.
Definitions
The functions and associated types are defined in the
ucontext.h
system
header file
An include directive instructs a text file processor to replace the directive text with the content of a specified file.
The act of including may be logical in nature. The processor may simply process the include file content at the location of ...
. This includes the
ucontext_t
type, with which all four functions operate:
typedef struct ucontext_t;
uc_link
points to the context which will be resumed when the current context exits, if the context was created with
makecontext
(a secondary context).
uc_sigmask
is used to store the set of
signal
A signal is both the process and the result of transmission of data over some media accomplished by embedding some variation. Signals are important in multiple subject fields including signal processing, information theory and biology.
In ...
s blocked in the context, and
uc_stack
is the
stack
Stack may refer to:
Places
* Stack Island, an island game reserve in Bass Strait, south-eastern Australia, in Tasmania’s Hunter Island Group
* Blue Stack Mountains, in Co. Donegal, Ireland
People
* Stack (surname) (including a list of people ...
used by the context.
uc_mcontext
stores
execution
Capital punishment, also known as the death penalty and formerly called judicial homicide, is the state-sanctioned killing of a person as punishment for actual or supposed misconduct. The sentence ordering that an offender be punished in ...
state
State most commonly refers to:
* State (polity), a centralized political organization that regulates law and society within a territory
**Sovereign state, a sovereign polity in international law, commonly referred to as a country
**Nation state, a ...
, including all
registers and
CPU flag
A flag is a piece of textile, fabric (most often rectangular) with distinctive colours and design. It is used as a symbol, a signalling device, or for decoration. The term ''flag'' is also used to refer to the graphic design employed, and fla ...
s, the
instruction pointer
The program counter (PC), commonly called the instruction pointer (IP) in Intel x86 and Itanium microprocessors, and sometimes called the instruction address register (IAR), the instruction counter, or just part of the instruction sequencer, is ...
, and the
stack pointer;
mcontext_t
is an
opaque type.
The functions are:
*
int setcontext(const ucontext_t *ucp)
*:This function transfers control to the context in
ucp
. Execution continues from the point at which the context was stored in
ucp
.
setcontext
does not return.
*
int getcontext(ucontext_t *ucp)
*:Saves current context into
ucp
. This function returns in two possible cases: after the initial call, or when a thread switches to the context in
ucp
via
setcontext
or
swapcontext
. The
getcontext
function does not provide a
return value
In computer programming, a return statement causes execution to leave the current subroutine and resume at the point in the code immediately after the instruction which called the subroutine, known as its return address. The return address is sav ...
to distinguish the cases (its return value is used solely to signal error), so the programmer must use an explicit flag variable, which must not be a register variable and must be declared
volatile to avoid
constant propagation or other
compiler optimization
An optimizing compiler is a compiler designed to generate code that is optimized in aspects such as minimizing program execution time, memory usage, storage size, and power consumption. Optimization is generally implemented as a sequence of op ...
s.
*
void makecontext(ucontext_t *ucp, void (*func)(), int argc, ...)
*:The
makecontext
function sets up an alternate thread of control in
ucp
, which has previously been initialised using
getcontext
. The
ucp.uc_stack
member should be pointed to an appropriately sized stack; the constant
SIGSTKSZ
is commonly used. When
ucp
is jumped to using
setcontext
or
swapcontext
, execution will begin at the
entry point
In computer programming, an entry point is the place in a program where the execution of a program begins, and where the program has access to command line arguments.
To start a program's execution, the loader or operating system passes co ...
to the function pointed to by
func
, with
argc
arguments as specified. When
func
terminates, control is returned to
ucp.uc_link
.
*
int swapcontext(ucontext_t *oucp, ucontext_t *ucp)
*:Transfers control to
ucp
and saves the current execution state into
oucp
.
Example
The example below demonstrates an iterator using
setcontext
.
#include
#include
#include
#include
/* The three contexts:
* (1) main_context1 : The point in main to which loop will return.
* (2) main_context2 : The point in main to which control from loop will
* flow by switching contexts.
* (3) loop_context : The point in loop to which control from main will
* flow by switching contexts. */
ucontext_t main_context1, main_context2, loop_context;
/* The iterator return value. */
volatile int i_from_iterator;
/* This is the iterator function. It is entered on the first call to
* swapcontext, and loops from 0 to 9. Each value is saved in i_from_iterator,
* and then swapcontext used to return to the main loop. The main loop prints
* the value and calls swapcontext to swap back into the function. When the end
* of the loop is reached, the function exits, and execution switches to the
* context pointed to by main_context1. */
void loop(
ucontext_t *loop_context,
ucontext_t *other_context,
int *i_from_iterator)
int main(void)
NOTE: this example is not correct,
[The Open Group Base Specifications Issue 6
IEEE Std 1003.1, 2004 Editio]
/ref> but may work as intended in some cases. The function makecontext
requires additional parameters to be type int
, but the example passes pointers. Thus, the example may fail on 64-bit machines (specifically LP64-architectures, where sizeof(void*) > sizeof(int)). This problem can be worked around by breaking up and reconstructing 64-bit values, but that introduces a performance penalty.
For get and set context, a smaller context can be handy:
#include
#include
#include
int main(int argc, const char *argv[])
This makes an infinite loop because context holds the program counter.
References
External links
System V Contexts
- The GNU C Library
The GNU C Library, commonly known as glibc, is the GNU Project implementation of the C standard library. It provides a wrapper around the system calls of the Linux kernel and other kernels for application use. Despite its name, it now also dir ...
Manual
*
*{{man, 3, setcontext, FreeBSD
Unix
Control flow
C (programming language) libraries
Articles with example C code
Threads (computing)