-
Notifications
You must be signed in to change notification settings - Fork 0
/
cco.c
72 lines (62 loc) · 1.65 KB
/
cco.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
68
69
70
71
72
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include "cco.h"
void context_switch(void **sp);
void context_init(void **sp,void *co);
#if defined(__unix__) && (defined(__i386__) || defined(__i686__))
typedef unsigned long machine_word_type;
#elif defined(__unix__) && (defined(__x86_64__) || defined(__amd64__))
typedef unsigned long machine_word_type;
#elif defined(__MINGW64__)
typedef unsigned long long machine_word_type;
#elif defined(__MINGW32__)
typedef unsigned long machine_word_type;
#else
#error "you have to define `machine_word_type` for you target"
#endif
cco* cco_create(cco_handle entry,long stack_size,void *arg)
{
cco *co = malloc(sizeof(*co));
if(co)
{
void *stack_top;
long sz = (stack_size + sizeof(machine_word_type) - 1) - (stack_size + sizeof(machine_word_type) - 1) % sizeof(machine_word_type);
co->stack = malloc(sz + sizeof(machine_word_type));
if(co->stack)
{
#ifdef STACK_GROW_UP
stack_top = co->sp = co->stack;
#else
stack_top = co->sp = co->stack + sz;
#endif
context_init(&(co->sp),co);
co->arg = arg;
co->entry = entry;
return co;
}
free(co);
}
return NULL;
}
void cco_entry(cco *co)
{
co->entry(co,co->arg);
co->ret = 0;
context_switch(&(co->sp));
}
int cco_resume(cco *co)
{
context_switch(&(co->sp));
return co->ret;
}
void cco_yield(cco *co)
{
co->ret = 1;
context_switch(&(co->sp));
}
void cco_release(cco *co)
{
free(co->stack);
free(co);
}