Setcontext
Encyclopedia : S : SE : SET : Setcontext
setcontext is one of a family of C library functions (the others being getcontext, makecontext and swapcontext) used for context control. setcontext et al allow the implementation in C of advanced control flow patterns such as iterators and coroutines.
setcontext et al can be viewed as a more advanced version of setjmp/longjmp; where the latter just allows a single non-local jump up the stack, setcontext allows the creation of multiple coöperative threads of control, each with their own stack.
Usage
The four function calls, along with the typesucontext_t and mcontext_t, are defined in <ucontext.h>.
The ucontext_t type stores execution state, including all registers and flags, the instruction pointer, and the stack pointer.
See below for an example of usage.
setcontext(const ucontext_t *ucp): transfer control to the context inucp. Does not return.getcontext(ucontext_t *ucp): store the current context intoucp. Will appear to return both after the initial call and whenever the context inucpis jumped to; unfortunately,getcontextdoes not provide a return value to distinguish the cases, so the programmer must use a flag variable (defined volatile, and not a register variable, for obvious reasons).makecontext(ucontext_t *ucp, void *func(), int argc, ...): set up an alternate thread of control, to be stored inucp(which should have been initialised withgetcontextfirst).ucp.uc_stackshould contain an appropriately sized stack.ucpwill begin control at the entry point tofunc, which will be called withargcarguments as supplied. Whenfuncterminates, control will pass toucp.uc_link.swapcontext(ucontext_t *oucp, ucontext_t *ucp): transfer control toucp, saving the current execution state intooucp.
Specification
setcontext et al are described in the Single Unix Specification, version 2. Not all Unix-like operating systems have the functions, a fact which has possibly led to their being little-used.Example
#include#include #include static void loop_iter (ucontext_t *my_ucp, ucontext_t *loop_ucp, int *yield_i) }
int main (void) }
return 0; }
See also
External links
- [System V Contexts] - The GNU C Library Manual
From Wikipedia, the Free Encyclopedia. Original article here. Support Wikipedia by contributing or donating.
All text is available under the terms of the GNU Free Documentation License See Wikipedia Copyrights for details.
