#include <ucontext.h>
void makecontext(ucontext_t *ucp, typeof(void (int arg0, ...)) *func,
int argc, ...);
int swapcontext(ucontext_t *restrict oucp,
const ucontext_t *restrict ucp);
makecontext() 関数は、ポインター ucp が指すコンテキストを変更する (ucp は以前の getcontext(3) 呼び出しで得られたものである)。 makecontext() を起動する前には、呼び出し者は、このコンテキスト用に 新しいスタックを確保し、そのアドレスを ucp->uc_stack に代入し、 さらに後継のコンテキストを定義し、そのアドレスを ucp->uc_link に 代入しなければならない。
このコンテキストが将来 (setcontext(3) または swapcontext() によって) 有効にされると、関数 func が呼ばれ、 引数として argc 以降の整数 (int) 引数の列が渡される。 呼び出し者は argc にこれらの引数の個数を指定しなければならない。 この関数が戻ると、後継のコンテキストが有効になる。 後継コンテキストのポインターが NULL の場合、そのスレッドが終了する。
swapcontext() 関数は現在のコンテキストを ポインター oucp が指す構造体に保存し、 ポインター ucp が指すコンテキストを有効にする。
| インターフェース | 属性 | 値 |
| makecontext() | Thread safety |
MT-Safe race:ucp
|
| swapcontext() | Thread safety |
MT-Safe race:oucp race:ucp
|
On architectures where int and pointer types are the same size (e.g., x86-32, where both types are 32 bits), you may be able to get away with passing pointers as arguments to makecontext() following argc. However, doing this is not guaranteed to be portable, is undefined according to the standards, and won't work on architectures where pointers are larger than ints. Nevertheless, starting with glibc 2.8, glibc makes some changes to makecontext(), to permit this on some 64-bit architectures (e.g., x86-64).
$ ./a.out main: swapcontext(&uctx_main, &uctx_func2) func2: started func2: swapcontext(&uctx_func2, &uctx_func1) func1: started func1: swapcontext(&uctx_func1, &uctx_func2) func2: returning func1: returning main: exiting
#include <err.h>
#include <stdio.h>
#include <stdlib.h>
#include <ucontext.h>
static ucontext_t uctx_main, uctx_func1, uctx_func2;
static void
func1(void)
{
printf("%s: started\n", __func__);
printf("%s: swapcontext(&uctx_func1, &uctx_func2)\n", __func__);
if (swapcontext(&uctx_func1, &uctx_func2) == -1)
err(EXIT_FAILURE, "swapcontext");
printf("%s: returning\n", __func__);
}
static void
func2(void)
{
printf("%s: started\n", __func__);
printf("%s: swapcontext(&uctx_func2, &uctx_func1)\n", __func__);
if (swapcontext(&uctx_func2, &uctx_func1) == -1)
err(EXIT_FAILURE, "swapcontext");
printf("%s: returning\n", __func__);
}
int
main(int argc, char *argv[])
{
char func1_stack[16384];
char func2_stack[16384];
if (getcontext(&uctx_func1) == -1)
err(EXIT_FAILURE, "getcontext");
uctx_func1.uc_stack.ss_sp = func1_stack;
uctx_func1.uc_stack.ss_size = sizeof(func1_stack);
uctx_func1.uc_link = &uctx_main;
makecontext(&uctx_func1, func1, 0);
if (getcontext(&uctx_func2) == -1)
err(EXIT_FAILURE, "getcontext");
uctx_func2.uc_stack.ss_sp = func2_stack;
uctx_func2.uc_stack.ss_size = sizeof(func2_stack);
/* Successor context is f1(), unless argc > 1 */
uctx_func2.uc_link = (argc > 1) ? NULL : &uctx_func1;
makecontext(&uctx_func2, func2, 0);
printf("%s: swapcontext(&uctx_main, &uctx_func2)\n", __func__);
if (swapcontext(&uctx_main, &uctx_func2) == -1)
err(EXIT_FAILURE, "swapcontext");
printf("%s: exiting\n", __func__);
exit(EXIT_SUCCESS);
}