-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcoroutine.h
More file actions
45 lines (38 loc) · 1.17 KB
/
coroutine.h
File metadata and controls
45 lines (38 loc) · 1.17 KB
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
#ifndef COROUTINE_H
#define COROUTINE_H
#include <ucontext.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/time.h>
#include <unistd.h>
#define COROUTINE_MAX 128
#define COROUTINE_STACK_SIZE (1024 * 64)
typedef void (*coroutine_func)(void *);
typedef struct coroutine
{
ucontext_t ctx;
void *stack;
coroutine_func func;
void *arg;
size_t stack_size;
int is_running;
long long start_time;
long long elapsed_time;
long long sleep_time; // Remaining sleep time (in milliseconds)
} coroutine_t;
typedef struct coroutine_scheduler
{
coroutine_t coroutines[COROUTINE_MAX];
int current_id;
int running_count;
ucontext_t main_ctx;
} coroutine_scheduler_t;
void coroutine_init(coroutine_scheduler_t *scheduler);
int coroutine_create(coroutine_scheduler_t *scheduler, coroutine_func func, void *arg);
void coroutine_yield(coroutine_scheduler_t *scheduler);
void coroutine_resume(coroutine_scheduler_t *scheduler, int id);
void coroutine_sleep(coroutine_scheduler_t *scheduler, int milliseconds);
void coroutine_statistics(coroutine_scheduler_t *scheduler);
void coroutine_destroy(coroutine_scheduler_t *scheduler);
#endif