felipec (owner)

Revisions

gist: 13493 Download_button fork
public
Public Clone URL: git://gist.github.com/13493.git
Embed All Files: show embed
C #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#ifndef TRANS_H
#define TRANS_H
 
#include <ucontext.h>
 
#include <stdbool.h>
#include <stdio.h>
 
struct task
{
    bool pending;
    char stack[SIGSTKSZ];
    ucontext_t context;
    ucontext_t main_context;
};
 
typedef void (*task_func) (struct task *t);
 
static inline struct task *
task_new (task_func func)
{
    struct task *t;
 
    t = calloc (sizeof (struct task), 1);
 
    getcontext (&t->context);
 
    t->context.uc_link = 0;
    t->context.uc_stack.ss_sp = t->stack;
    t->context.uc_stack.ss_size = sizeof (t->stack);
    t->context.uc_stack.ss_flags = 0;
 
    makecontext (&t->context, (void (*)()) func, 1, t);
 
    swapcontext (&t->main_context, &t->context);
 
    return t;
}
 
static inline void
task_free (struct task *t)
{
    free (t);
}
 
static inline void
task_yield (struct task *t)
{
    t->pending = true;
    swapcontext (&t->context, &t->main_context);
}
 
static inline void
task_complete (struct task *t)
{
    t->pending = false;
    swapcontext (&t->context, &t->main_context);
}
 
static inline void
task_handle (struct task *t)
{
    if (t->pending)
        swapcontext (&t->main_context, &t->context);
}
 
#endif /* TRANS_H */