setcontext is one of a family of
C library
A library is a collection of materials, books or media that are accessible for use and not just for display purposes. A library provides physical (hard copies) or digital access (soft copies) materials, and may be a physical location or a vi ...
functions (the others being getcontext, makecontext and swapcontext) used for
context
Context may refer to:
* Context (language use), the relevant constraints of the communicative situation that influence language use, language variation, and discourse summary
Computing
* Context (computing), the virtual environment required to s ...
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 li ...
s such as
iterator
In computer programming, an iterator is an object that enables a programmer to traverse a container, particularly lists. Various types of iterators are often provided via a container's interface. Though the interface and semantics of a given ite ...
s,
fibers
Fiber or fibre (from la, fibra, links=no) 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 incorporate ...
, and
coroutine
Coroutines are computer program components that generalize subroutines for non-preemptive multitasking, by allowing execution to be suspended and resumed. Coroutines are well-suited for implementing familiar program components such as cooperative ...
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-op, or coop) is "an autonomous association of persons united voluntarily to meet their common economic, social and cultural needs and aspirations through a jointly owned and democratically-contro ...
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 both the system- and user-level application programming inte ...
.1-2001 and the
Single Unix Specification, version 2, but not all
Unix-like
A Unix-like (sometimes referred to as UN*X 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 Unix-li ...
operating system
An operating system (OS) is system software that manages computer hardware, software resources, and provides common daemon (computing), services for computer programs.
Time-sharing operating systems scheduler (computing), schedule tasks for ef ...
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 both the system- and user-level application programming inte ...
.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 both the system- and user-level application programming inte ...
.1-2008 they were removed, with
POSIX Threads
POSIX Threads, commonly known as pthreads, is an execution model that exists independently from a language, as well as a parallel execution model. It allows a program to control multiple different flows of work that overlap in time. Each flow of ...
indicated as a possible replacement. Citing IEEE Std 1003.1, 2004 Edition:
With the incorporation of the ISO/IEC 9899:1999 standard into this specification it was found that the ISO C standard (Subclause 6.11.6) specifies that the use of function declarators with empty parentheses is an obsolescent feature. Therefore, using the function prototype:
:void makecontext(ucontext_t *ucp, void (*func)(), int argc, ...);
is making use of an obsolescent feature of the ISO C standard. Therefore, a strictly conforming POSIX application cannot use this form. Therefore, use of getcontext(), makecontext(), and swapcontext() is marked obsolescent.
There is no way in the ISO C standard to specify a non-obsolescent function prototype indicating that a function will be called with an arbitrary number (including zero) of arguments of arbitrary types (including integers, pointers to data, pointers to functions, and composite types).
Definitions
The functions and associated types are defined in the
ucontext.h
system
header file
Many programming languages and other computer files have a directive, often called include (sometimes copy or import), that causes the contents of the specified file to be inserted into the original file. These included files are called copybooks ...
. 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
In signal processing, a signal is a function that conveys information about a phenomenon. Any quantity that can vary over space or time can be used as a signal to share messages between observers. The '' IEEE Transactions on Signal Processing' ...
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, is the state-sanctioned practice of deliberately killing a person as a punishment for an actual or supposed crime, usually following an authorized, rule-governed process to conclude that t ...
state
State may refer to:
Arts, entertainment, and media Literature
* ''State Magazine'', a monthly magazine published by the U.S. Department of State
* ''The State'' (newspaper), a daily newspaper in Columbia, South Carolina, United States
* '' Our ...
, including all
registers and
CPU
A central processing unit (CPU), also called a central processor, main processor or just processor, is the electronic circuitry that executes instructions comprising a computer program. The CPU performs basic arithmetic, logic, controlling, an ...
flag
A flag is a piece of fabric (most often rectangular or quadrilateral) with a distinctive design and colours. It is used as a symbol, a signalling device, or for decoration. The term ''flag'' is also used to refer to the graphic design emp ...
s, the
instruction pointer, and the
stack pointer
In computer science, a call stack is a stack data structure that stores information about the active subroutines of a computer program. This kind of stack is also known as an execution stack, program stack, control stack, run-time stack, or mach ...
;
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 s ...
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
In computing, an optimizing compiler is a compiler that tries to minimize or maximize some attributes of an executable computer program. Common requirements are to minimize a program's execution time, memory footprint, storage size, and power c ...
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 c ...
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's implementation of the C standard library. Despite its name, it now also directly supports C++ (and, indirectly, other programming languages). It was started in the 1980s by ...
Manual
*
*{{man, 3, setcontext, FreeBSD
Unix
Control flow
C (programming language) libraries
Articles with example C code
Threads (computing)