-
Notifications
You must be signed in to change notification settings - Fork 2
/
coro.h
81 lines (67 loc) · 1.63 KB
/
coro.h
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#include <stdint.h>
#include <ucontext.h>
int _Ux86_64_getcontext(ucontext_t *ucp);
int _Ux86_64_setcontext(const ucontext_t *ucp);
typedef struct coro_t_ coro_t;
typedef struct thread_t_ thread_t;
typedef enum {
CORO_NEW,
CORO_RUNNING,
CORO_FINISHED
} coro_state_t;
#ifdef __x86_64__
union ptr_splitter {
void *ptr;
uint32_t part[sizeof(void *) / sizeof(uint32_t)];
};
#endif
struct thread_t_ {
struct {
ucontext_t callee, caller;
} coro;
};
struct coro_t_ {
coro_state_t state;
void *function;
thread_t *thread;
ucontext_t context;
char *stack;
uint64_t yield_value;
};
#define STACK_SIZE (1 << 22)
static const int default_stack_size = (1 << 22);
void coro_yield(coro_t *coro, uint64_t value);
int swapcontext2(ucontext_t *oucp, ucontext_t *ucp) {
volatile char swapped = 0;
int result = _Ux86_64_getcontext(oucp);
if (result == 0 && !swapped) {
swapped = 1;
result = _Ux86_64_setcontext(ucp);
}
return result;
}
uint64_t
coro_resume(coro_t *coro)
{
if (coro->state == CORO_NEW)
coro->state = CORO_RUNNING;
else if (coro->state == CORO_FINISHED)
return 0;
ucontext_t old_context = coro->thread->coro.caller;
swapcontext2(&coro->thread->coro.caller, &coro->context);
coro->context = coro->thread->coro.callee;
coro->thread->coro.caller = old_context;
return coro->yield_value;
}
void
coro_yield(coro_t *coro, uint64_t value)
{
coro->yield_value = value;
swapcontext2(&coro->thread->coro.callee, &coro->thread->coro.caller);
}
void
coro_free(coro_t *coro)
{
// free(coro->stack);
free(coro);
}