forked from Winnerhust/uthread
-
Notifications
You must be signed in to change notification settings - Fork 0
/
uthread.h
88 lines (71 loc) · 1.93 KB
/
uthread.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
82
83
84
85
86
87
88
/**
* @file thread.h
* @author chenxueyou
* @version 0.1
* @brief :A asymmetric coroutine library for C++
* History
* 1. Date: 2014-12-12
* Author: chenxueyou
* Modification: this file was created
*/
#ifndef MY_UTHREAD_H
#define MY_UTHREAD_H
#ifdef __APPLE__
#define _XOPEN_SOURCE
#endif
#include <ucontext.h>
#include <vector>
#define DEFAULT_STACK_SZIE (1024*128)
#define MAX_UTHREAD_SIZE 1024
enum ThreadState{FREE,RUNNABLE,RUNNING,SUSPEND};
struct schedule_t;
typedef void (*Fun)(void *arg);
typedef struct uthread_t
{
ucontext_t ctx;
Fun func;
void *arg;
enum ThreadState state;
char stack[DEFAULT_STACK_SZIE];
}uthread_t;
typedef struct schedule_t
{
ucontext_t main;
int running_thread;
uthread_t *threads;
int max_index; // 曾经使用到的最大的index + 1
schedule_t():running_thread(-1), max_index(0) {
threads = new uthread_t[MAX_UTHREAD_SIZE];
for (int i = 0; i < MAX_UTHREAD_SIZE; i++) {
threads[i].state = FREE;
}
}
~schedule_t() {
delete [] threads;
}
}schedule_t;
/*help the thread running in the schedule*/
static void uthread_body(schedule_t *ps);
/*Create a user's thread
* @param[in]:
* schedule_t &schedule
* Fun func: user's function
* void *arg: the arg of user's function
* @param[out]:
* @return:
* return the index of the created thread in schedule
*/
int uthread_create(schedule_t &schedule,Fun func,void *arg);
/* Hang the currently running thread, switch to main thread */
void uthread_yield(schedule_t &schedule);
/* resume the thread which index equal id*/
void uthread_resume(schedule_t &schedule,int id);
/*test whether all the threads in schedule run over
* @param[in]:
* const schedule_t & schedule
* @param[out]:
* @return:
* return 1 if all threads run over,otherwise return 0
*/
int schedule_finished(const schedule_t &schedule);
#endif