TheRiver | blog

You have reached the world's edge, none but devils play past here

0%

协程

参考

协程的好处有哪些

协程原理解析(1)

云风的coroutine实现

协程那些事儿

context族函数

ucontext_t

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
/* Userlevel context.  */
typedef struct ucontext_t
{
unsigned long int __ctx(uc_flags);
struct ucontext_t *uc_link;
stack_t uc_stack;
mcontext_t uc_mcontext;
sigset_t uc_sigmask;
} ucontext_t;

/* Structure describing a signal stack. */
typedef struct
{
void *ss_sp;
int ss_flags;
size_t ss_size;
} stack_t;

/* Context to describe whole processor state. */
typedef struct
{
gregset_t __ctx(gregs);
/* Note that fpregs is a pointer. */
fpregset_t __ctx(fpregs);
__extension__ unsigned long long __reserved1 [8];
} mcontext_t;

typedef greg_t gregset_t[23];
__extension__ typedef long long int greg_t;
typedef struct _libc_fpstate *fpregset_t;

getcontext

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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
/* Get user context and store it in variable pointed to by UCP.  */
extern int getcontext (ucontext_t *__ucp) __THROWNL;

/* Save current context.
Copyright (C) 2002-2019 Free Software Foundation, Inc.
This file is part of the GNU C Library.
Contributed by Andreas Jaeger <aj@suse.de>, 2002.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<http://www.gnu.org/licenses/>. */
#include <sysdep.h>
#include <asm/prctl.h>
#include "ucontext_i.h"
/* int __getcontext (ucontext_t *ucp)
Saves the machine context in UCP such that when it is activated,
it appears as if __getcontext() returned again.
This implementation is intended to be used for *synchronous* context
switches only. Therefore, it does not have to save anything
other than the PRESERVED state. */
ENTRY(__getcontext)
/* Save the preserved registers, the registers used for passing
args, and the return address. */
movq %rbx, oRBX(%rdi)
movq %rbp, oRBP(%rdi)
movq %r12, oR12(%rdi)
movq %r13, oR13(%rdi)
movq %r14, oR14(%rdi)
movq %r15, oR15(%rdi)
movq %rdi, oRDI(%rdi)
movq %rsi, oRSI(%rdi)
movq %rdx, oRDX(%rdi)
movq %rcx, oRCX(%rdi)
movq %r8, oR8(%rdi)
movq %r9, oR9(%rdi)
movq (%rsp), %rcx
movq %rcx, oRIP(%rdi)
leaq 8(%rsp), %rcx /* Exclude the return address. */
movq %rcx, oRSP(%rdi)
#if SHSTK_ENABLED
/* Check if shadow stack is enabled. */
testl $X86_FEATURE_1_SHSTK, %fs:FEATURE_1_OFFSET
jz L(no_shstk)
/* Save RDI in RDX which won't be clobbered by syscall. */
movq %rdi, %rdx
xorl %eax, %eax
cmpq %fs:SSP_BASE_OFFSET, %rax
jnz L(shadow_stack_bound_recorded)
/* Get the base address and size of the default shadow stack
which must be the current shadow stack since nothing has
been recorded yet. */
sub $24, %RSP_LP
mov %RSP_LP, %RSI_LP
movl $ARCH_CET_STATUS, %edi
movl $__NR_arch_prctl, %eax
syscall
testq %rax, %rax
jz L(continue_no_err)
/* This should never happen. */
hlt
L(continue_no_err):
/* Record the base of the current shadow stack. */
movq 8(%rsp), %rax
movq %rax, %fs:SSP_BASE_OFFSET
add $24, %RSP_LP
/* Restore RDI. */
movq %rdx, %rdi
L(shadow_stack_bound_recorded):
/* Get the current shadow stack pointer. */
rdsspq %rax
/* NB: Save the caller's shadow stack so that we can jump back
to the caller directly. */
addq $8, %rax
movq %rax, oSSP(%rdx)
/* Save the current shadow stack base in ucontext. */
movq %fs:SSP_BASE_OFFSET, %rax
movq %rax, (oSSP + 8)(%rdi)
L(no_shstk):
#endif
/* We have separate floating-point register content memory on the
stack. We use the __fpregs_mem block in the context. Set the
links up correctly. */
leaq oFPREGSMEM(%rdi), %rcx
movq %rcx, oFPREGS(%rdi)
/* Save the floating-point environment. */
fnstenv (%rcx)
fldenv (%rcx)
stmxcsr oMXCSR(%rdi)
/* Save the current signal mask with
rt_sigprocmask (SIG_BLOCK, NULL, set,_NSIG/8). */
leaq oSIGMASK(%rdi), %rdx
xorl %esi,%esi
#if SIG_BLOCK == 0
xorl %edi, %edi
#else
movl $SIG_BLOCK, %edi
#endif
movl $_NSIG8,%r10d
movl $__NR_rt_sigprocmask, %eax
syscall
cmpq $-4095, %rax /* Check %rax for error. */
jae SYSCALL_ERROR_LABEL /* Jump to error handler if error. */
/* All done, return 0 for success. */
xorl %eax, %eax
ret
PSEUDO_END(__getcontext)
weak_alias (__getcontext, getcontext)

makecontext

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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
/* Manipulate user context UCP to continue with calling functions FUNC
and the ARGC-1 parameters following ARGC when the context is used
the next time in `setcontext' or `swapcontext'.

We cannot say anything about the parameters FUNC takes; `void'
is as good as any other choice. */
extern void makecontext (ucontext_t *__ucp, void (*__func) (void),
int __argc, ...) __THROW;

/* This implementation can handle any ARGC value but only
normal integer parameters.
makecontext sets up a stack and the registers for the
user context. The stack looks like this:
+-----------------------+
| next context |
+-----------------------+
| parameter 7-n |
+-----------------------+
| trampoline address |
%rsp -> +-----------------------+

The registers are set up like this:
%rdi,%rsi,%rdx,%rcx,%r8,%r9: parameter 1 to 6
%rbx : address of next context
%rsp : stack pointer.
*/

/* XXX: This implementation currently only handles integer arguments.
To handle long int and pointer arguments the va_arg arguments needs
to be changed to long and also the stdlib/tst-setcontext.c file needs
to be changed to pass long arguments to makecontext. */


void
__makecontext (ucontext_t *ucp, void (*func) (void), int argc, ...)
{
extern void __start_context (void) attribute_hidden;
extern void __push___start_context (ucontext_t *)
attribute_hidden;
greg_t *sp;
unsigned int idx_uc_link;
va_list ap;
int i;

/* Generate room on stack for parameter if needed and uc_link. */
sp = (greg_t *) ((uintptr_t) ucp->uc_stack.ss_sp
+ ucp->uc_stack.ss_size);
sp -= (argc > 6 ? argc - 6 : 0) + 1;
/* Align stack and make space for trampoline address. */
sp = (greg_t *) ((((uintptr_t) sp) & -16L) - 8);

idx_uc_link = (argc > 6 ? argc - 6 : 0) + 1;

/* Setup context ucp. */
/* Address to jump to. */
ucp->uc_mcontext.gregs[REG_RIP] = (uintptr_t) func;
/* Setup rbx.*/
ucp->uc_mcontext.gregs[REG_RBX] = (uintptr_t) &sp[idx_uc_link];
ucp->uc_mcontext.gregs[REG_RSP] = (uintptr_t) sp;

/* Setup stack. */
#if SHSTK_ENABLED
struct pthread *self = THREAD_SELF;
unsigned int feature_1 = THREAD_GETMEM (self, header.feature_1);
/* NB: We must check feature_1 before accessing __ssp since caller
may be compiled against ucontext_t without __ssp. */
if ((feature_1 & X86_FEATURE_1_SHSTK) != 0)
{
/* Shadow stack is enabled. We need to allocate a new shadow
stack. */
unsigned long ssp_size = (((uintptr_t) sp
- (uintptr_t) ucp->uc_stack.ss_sp)
>> STACK_SIZE_TO_SHADOW_STACK_SIZE_SHIFT);
/* Align shadow stack to 8 bytes. */
ssp_size = ALIGN_UP (ssp_size, 8);

ucp->__ssp[1] = ssp_size;
ucp->__ssp[2] = ssp_size;

/* Call __push___start_context to allocate a new shadow stack,
push __start_context onto the new stack as well as the new
shadow stack. NB: After __push___start_context returns,
ucp->__ssp[0]: The new shadow stack pointer.
ucp->__ssp[1]: The base address of the new shadow stack.
ucp->__ssp[2]: The size of the new shadow stack.
*/
__push___start_context (ucp);
}
else
#endif
sp[0] = (uintptr_t) &__start_context;
sp[idx_uc_link] = (uintptr_t) ucp->uc_link;

va_start (ap, argc);
/* Handle arguments.

The standard says the parameters must all be int values. This is
an historic accident and would be done differently today. For
x86-64 all integer values are passed as 64-bit values and
therefore extending the API to copy 64-bit values instead of
32-bit ints makes sense. It does not break existing
functionality and it does not violate the standard which says
that passing non-int values means undefined behavior. */
for (i = 0; i < argc; ++i)
switch (i)
{
case 0:
ucp->uc_mcontext.gregs[REG_RDI] = va_arg (ap, greg_t);
break;
case 1:
ucp->uc_mcontext.gregs[REG_RSI] = va_arg (ap, greg_t);
break;
case 2:
ucp->uc_mcontext.gregs[REG_RDX] = va_arg (ap, greg_t);
break;
case 3:
ucp->uc_mcontext.gregs[REG_RCX] = va_arg (ap, greg_t);
break;
case 4:
ucp->uc_mcontext.gregs[REG_R8] = va_arg (ap, greg_t);
break;
case 5:
ucp->uc_mcontext.gregs[REG_R9] = va_arg (ap, greg_t);
break;
default:
/* Put value on stack. */
sp[i - 5] = va_arg (ap, greg_t);
break;
}
va_end (ap);

}

  • uc_link存放的是下一个要执行的上下文的地址,如果uc_link为NULL,则当前ucontext执行完,线程就退出了
  • uc_stack是即将运行的func使用的堆栈空间,不同于函数递归使用一个栈可能引起的栈溢出,这里栈空间可以自行分配

setcontext

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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
/* Set user context from information of variable pointed to by UCP.  */
extern int setcontext (const ucontext_t *__ucp) __THROWNL;

/* Install given context.
Copyright (C) 2002-2019 Free Software Foundation, Inc.
This file is part of the GNU C Library.
Contributed by Andreas Jaeger <aj@suse.de>, 2002.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<http://www.gnu.org/licenses/>. */
#include <sysdep.h>
#include <asm/prctl.h>
#include "ucontext_i.h"
/* int __setcontext (const ucontext_t *ucp)
Restores the machine context in UCP and thereby resumes execution
in that context.
This implementation is intended to be used for *synchronous* context
switches only. Therefore, it does not have to restore anything
other than the PRESERVED state. */
ENTRY(__setcontext)
/* Save argument since syscall will destroy it. */
pushq %rdi
cfi_adjust_cfa_offset(8)
/* Set the signal mask with
rt_sigprocmask (SIG_SETMASK, mask, NULL, _NSIG/8). */
leaq oSIGMASK(%rdi), %rsi
xorl %edx, %edx
movl $SIG_SETMASK, %edi
movl $_NSIG8,%r10d
movl $__NR_rt_sigprocmask, %eax
syscall
/* Pop the pointer into RDX. The choice is arbitrary, but
leaving RDI and RSI available for use later can avoid
shuffling values. */
popq %rdx
cfi_adjust_cfa_offset(-8)
cmpq $-4095, %rax /* Check %rax for error. */
jae SYSCALL_ERROR_LABEL /* Jump to error handler if error. */
/* Restore the floating-point context. Not the registers, only the
rest. */
movq oFPREGS(%rdx), %rcx
fldenv (%rcx)
ldmxcsr oMXCSR(%rdx)
/* Load the new stack pointer, the preserved registers and
registers used for passing args. */
cfi_def_cfa(%rdx, 0)
cfi_offset(%rbx,oRBX)
cfi_offset(%rbp,oRBP)
cfi_offset(%r12,oR12)
cfi_offset(%r13,oR13)
cfi_offset(%r14,oR14)
cfi_offset(%r15,oR15)
cfi_offset(%rsp,oRSP)
cfi_offset(%rip,oRIP)
movq oRSP(%rdx), %rsp
movq oRBX(%rdx), %rbx
movq oRBP(%rdx), %rbp
movq oR12(%rdx), %r12
movq oR13(%rdx), %r13
movq oR14(%rdx), %r14
movq oR15(%rdx), %r15
#if SHSTK_ENABLED
/* Check if shadow stack is enabled. */
testl $X86_FEATURE_1_SHSTK, %fs:FEATURE_1_OFFSET
jz L(no_shstk)
/* If the base of the target shadow stack is the same as the
base of the current shadow stack, we unwind the shadow
stack. Otherwise it is a stack switch and we look for a
restore token. */
movq oSSP(%rdx), %rsi
movq %rsi, %rdi
/* Get the base of the target shadow stack. */
movq (oSSP + 8)(%rdx), %rcx
cmpq %fs:SSP_BASE_OFFSET, %rcx
je L(unwind_shadow_stack)
L(find_restore_token_loop):
/* Look for a restore token. */
movq -8(%rsi), %rax
andq $-8, %rax
cmpq %rsi, %rax
je L(restore_shadow_stack)
/* Try the next slot. */
subq $8, %rsi
jmp L(find_restore_token_loop)
L(restore_shadow_stack):
/* Pop return address from the shadow stack since setcontext
will not return. */
movq $1, %rax
incsspq %rax
/* Use the restore stoken to restore the target shadow stack. */
rstorssp -8(%rsi)
/* Save the restore token on the old shadow stack. NB: This
restore token may be checked by setcontext or swapcontext
later. */
saveprevssp
/* Record the new shadow stack base that was switched to. */
movq (oSSP + 8)(%rdx), %rax
movq %rax, %fs:SSP_BASE_OFFSET
L(unwind_shadow_stack):
rdsspq %rcx
subq %rdi, %rcx
je L(skip_unwind_shadow_stack)
negq %rcx
shrq $3, %rcx
movl $255, %esi
L(loop):
cmpq %rsi, %rcx
cmovb %rcx, %rsi
incsspq %rsi
subq %rsi, %rcx
ja L(loop)
L(skip_unwind_shadow_stack):
movq oRSI(%rdx), %rsi
movq oRDI(%rdx), %rdi
movq oRCX(%rdx), %rcx
movq oR8(%rdx), %r8
movq oR9(%rdx), %r9
/* Get the return address set with getcontext. */
movq oRIP(%rdx), %r10
/* Setup finally %rdx. */
movq oRDX(%rdx), %rdx
/* Check if return address is valid for the case when setcontext
is invoked from __start_context with linked context. */
rdsspq %rax
cmpq (%rax), %r10
/* Clear RAX to indicate success. NB: Don't use xorl to keep
EFLAGS for jne. */
movl $0, %eax
jne L(jmp)
/* Return to the new context if return address valid. */
pushq %r10
ret
L(jmp):
/* Jump to the new context directly. */
jmp *%r10
L(no_shstk):
#endif
/* The following ret should return to the address set with
getcontext. Therefore push the address on the stack. */
movq oRIP(%rdx), %rcx
pushq %rcx
movq oRSI(%rdx), %rsi
movq oRDI(%rdx), %rdi
movq oRCX(%rdx), %rcx
movq oR8(%rdx), %r8
movq oR9(%rdx), %r9
/* Setup finally %rdx. */
movq oRDX(%rdx), %rdx
/* End FDE here, we fall into another context. */
cfi_endproc
cfi_startproc
/* Clear rax to indicate success. */
xorl %eax, %eax
ret
PSEUDO_END(__setcontext)
weak_alias (__setcontext, setcontext)

swapcontext

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
/* Save current context in context variable pointed to by OUCP and set
context from variable pointed to by UCP. */
extern int swapcontext (ucontext_t *__restrict __oucp,
const ucontext_t *__restrict __ucp)

//hppa实现
int
__swapcontext (ucontext_t *oucp, const ucontext_t *ucp)
{
/* Save the current machine context to oucp. */
__getcontext (oucp);

/* mark sc_sar flag to skip the setcontext call on reactivation. */
if (oucp->uc_mcontext.sc_sar == 0) {
oucp->uc_mcontext.sc_sar++;

/* Restore the machine context in ucp. */
__setcontext (ucp);
}

return 0;
}


//ia64实现
int
__swapcontext (ucontext_t *oucp, const ucontext_t *ucp)
{
struct rv rv = __getcontext (oucp);
if (rv.first_return)
__setcontext (ucp);
return 0;
}

云风源码研读

TODO

coroutine.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
#include "coroutine.h"
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <stddef.h>
#include <string.h>
#include <stdint.h>

#if __APPLE__ && __MACH__
#include <sys/ucontext.h>
#else
#include <ucontext.h>
#endif

#define STACK_SIZE (1024*1024)
#define DEFAULT_COROUTINE 16

struct coroutine;

struct schedule {
char stack[STACK_SIZE];
ucontext_t main;
int nco;
int cap;
int running;
struct coroutine **co;
};

struct coroutine {
coroutine_func func;
void *ud;
ucontext_t ctx;
struct schedule * sch;
ptrdiff_t cap;
ptrdiff_t size;
int status;
char *stack;
};

struct coroutine *
_co_new(struct schedule *S , coroutine_func func, void *ud) {
struct coroutine * co = malloc(sizeof(*co));
co->func = func;
co->ud = ud;
co->sch = S;
co->cap = 0;
co->size = 0;
co->status = COROUTINE_READY;
co->stack = NULL;
return co;
}

void
_co_delete(struct coroutine *co) {
free(co->stack);
free(co);
}

struct schedule *
coroutine_open(void) {
struct schedule *S = malloc(sizeof(*S));
S->nco = 0;
S->cap = DEFAULT_COROUTINE;
S->running = -1;
S->co = malloc(sizeof(struct coroutine *) * S->cap);
memset(S->co, 0, sizeof(struct coroutine *) * S->cap);
return S;
}

void
coroutine_close(struct schedule *S) {
int i;
for (i=0;i<S->cap;i++) {
struct coroutine * co = S->co[i];
if (co) {
_co_delete(co);
}
}
free(S->co);
S->co = NULL;
free(S);
}

int
coroutine_new(struct schedule *S, coroutine_func func, void *ud) {
struct coroutine *co = _co_new(S, func , ud);
if (S->nco >= S->cap) {
int id = S->cap;
S->co = realloc(S->co, S->cap * 2 * sizeof(struct coroutine *));
memset(S->co + S->cap , 0 , sizeof(struct coroutine *) * S->cap);
S->co[S->cap] = co;
S->cap *= 2;
++S->nco;
return id;
} else {
int i;
for (i=0;i<S->cap;i++) {
int id = (i+S->nco) % S->cap;
if (S->co[id] == NULL) {
S->co[id] = co;
++S->nco;
return id;
}
}
}
assert(0);
return -1;
}

static void
mainfunc(uint32_t low32, uint32_t hi32) {
uintptr_t ptr = (uintptr_t)low32 | ((uintptr_t)hi32 << 32);
struct schedule *S = (struct schedule *)ptr;
int id = S->running;
struct coroutine *C = S->co[id];
C->func(S,C->ud);
_co_delete(C);
S->co[id] = NULL;
--S->nco;
S->running = -1;
}

void
coroutine_resume(struct schedule * S, int id) {
assert(S->running == -1);
assert(id >=0 && id < S->cap);
struct coroutine *C = S->co[id];
if (C == NULL)
return;
int status = C->status;
switch(status) {
case COROUTINE_READY:
getcontext(&C->ctx);
C->ctx.uc_stack.ss_sp = S->stack;
C->ctx.uc_stack.ss_size = STACK_SIZE;
C->ctx.uc_link = &S->main;
S->running = id;
C->status = COROUTINE_RUNNING;
uintptr_t ptr = (uintptr_t)S;
makecontext(&C->ctx, (void (*)(void)) mainfunc, 2, (uint32_t)ptr, (uint32_t)(ptr>>32));
swapcontext(&S->main, &C->ctx);
break;
case COROUTINE_SUSPEND:
memcpy(S->stack + STACK_SIZE - C->size, C->stack, C->size);
S->running = id;
C->status = COROUTINE_RUNNING;
swapcontext(&S->main, &C->ctx);
break;
default:
assert(0);
}
}

static void
_save_stack(struct coroutine *C, char *top) {
char dummy = 0;
assert(top - &dummy <= STACK_SIZE);
if (C->cap < top - &dummy) {
free(C->stack);
C->cap = top-&dummy;
C->stack = malloc(C->cap);
}
C->size = top - &dummy;
memcpy(C->stack, &dummy, C->size);
}

void
coroutine_yield(struct schedule * S) {
int id = S->running;
assert(id >= 0);
struct coroutine * C = S->co[id];
assert((char *)&C > S->stack);
_save_stack(C,S->stack + STACK_SIZE);
C->status = COROUTINE_SUSPEND;
S->running = -1;
swapcontext(&C->ctx , &S->main);
}

int
coroutine_status(struct schedule * S, int id) {
assert(id>=0 && id < S->cap);
if (S->co[id] == NULL) {
return COROUTINE_DEAD;
}
return S->co[id]->status;
}

int
coroutine_running(struct schedule * S) {
return S->running;
}

coroutine.h

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#ifndef C_COROUTINE_H
#define C_COROUTINE_H

#define COROUTINE_DEAD 0
#define COROUTINE_READY 1
#define COROUTINE_RUNNING 2
#define COROUTINE_SUSPEND 3

struct schedule;

typedef void (*coroutine_func)(struct schedule *, void *ud);

struct schedule * coroutine_open(void);
void coroutine_close(struct schedule *);

int coroutine_new(struct schedule *, coroutine_func, void *ud);
void coroutine_resume(struct schedule *, int id);
int coroutine_status(struct schedule *, int id);
int coroutine_running(struct schedule *);
void coroutine_yield(struct schedule *);

#endif

main.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
#include "coroutine.h"
#include <stdio.h>

struct args {
int n;
};

static void
foo(struct schedule * S, void *ud) {
struct args * arg = ud;
int start = arg->n;
int i;
for (i=0;i<5;i++) {
printf("coroutine %d : %d\n",coroutine_running(S) , start + i);
coroutine_yield(S);
}
}

static void
test(struct schedule *S) {
struct args arg1 = { 0 };
struct args arg2 = { 100 };

int co1 = coroutine_new(S, foo, &arg1);
int co2 = coroutine_new(S, foo, &arg2);
printf("main start\n");
while (coroutine_status(S,co1) && coroutine_status(S,co2)) {
coroutine_resume(S,co1);
coroutine_resume(S,co2);
}
printf("main end\n");
}

int
main() {
struct schedule * S = coroutine_open();
test(S);
coroutine_close(S);

return 0;
}

ending

78601467_p0.jpg

----------- ending -----------