-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcoroutine.c
108 lines (100 loc) · 2.96 KB
/
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
#include "coroutine.h"
static long long get_current_time_ms()
{
struct timeval tv;
gettimeofday(&tv, NULL);
return tv.tv_sec * 1000 + tv.tv_usec / 1000;
}
void coroutine_init(coroutine_scheduler_t *scheduler)
{
memset(scheduler, 0, sizeof(coroutine_scheduler_t));
scheduler->current_id = -1;
}
int coroutine_create(coroutine_scheduler_t *scheduler, coroutine_func func, void *arg)
{
for (int i = 0; i < COROUTINE_MAX; ++i)
{
if (!scheduler->coroutines[i].is_running)
{
coroutine_t *co = &scheduler->coroutines[i];
co->stack = malloc(COROUTINE_STACK_SIZE);
if (!co->stack)
{
perror("Failed to allocate coroutine stack");
return -1;
}
getcontext(&co->ctx);
co->ctx.uc_stack.ss_sp = co->stack;
co->ctx.uc_stack.ss_size = COROUTINE_STACK_SIZE;
co->ctx.uc_link = &scheduler->main_ctx;
co->func = func;
co->arg = arg;
co->stack_size = COROUTINE_STACK_SIZE;
co->is_running = 1;
co->start_time = 0;
co->elapsed_time = 0;
co->sleep_time = 0;
makecontext(&co->ctx, (void (*)())func, 1, arg);
scheduler->running_count++;
return i;
}
}
fprintf(stderr, "Too many coroutines!\n");
return -1;
}
void coroutine_yield(coroutine_scheduler_t *scheduler)
{
int current_id = scheduler->current_id;
if (current_id != -1)
{
coroutine_t *co = &scheduler->coroutines[current_id];
co->elapsed_time += get_current_time_ms() - co->start_time;
scheduler->current_id = -1;
swapcontext(&co->ctx, &scheduler->main_ctx);
}
}
void coroutine_resume(coroutine_scheduler_t *scheduler, int id)
{
coroutine_t *co = &scheduler->coroutines[id];
scheduler->current_id = id;
co->start_time = get_current_time_ms();
swapcontext(&scheduler->main_ctx, &co->ctx);
if (!co->is_running)
{ // Coroutine has exited
scheduler->running_count--;
free(co->stack);
memset(co, 0, sizeof(coroutine_t));
}
}
void coroutine_sleep(coroutine_scheduler_t *scheduler, int milliseconds)
{
int current_id = scheduler->current_id;
if (current_id != -1)
{
coroutine_t *co = &scheduler->coroutines[current_id];
co->sleep_time = milliseconds;
coroutine_yield(scheduler);
}
}
void coroutine_statistics(coroutine_scheduler_t *scheduler)
{
for (int i = 0; i < COROUTINE_MAX; ++i)
{
coroutine_t *co = &scheduler->coroutines[i];
if (co->is_running)
{
printf("Coroutine %d: elapsed time = %lld ms\n", i, co->elapsed_time);
}
}
}
void coroutine_destroy(coroutine_scheduler_t *scheduler)
{
for (int i = 0; i < COROUTINE_MAX; ++i)
{
coroutine_t *co = &scheduler->coroutines[i];
if (co->is_running)
{
free(co->stack);
}
}
}