-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsimple_task_manager.c
146 lines (121 loc) · 2.68 KB
/
simple_task_manager.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
#include <setjmp.h>
#include <stdio.h>
/**
* Type definitions
*/
typedef void (task_func_t)(void);
typedef enum {
TASK_STATE_NONE,
TASK_STATE_IDLE,
TASK_STATE_RUNNING,
TASK_STATE_PAUSED,
TASK_STATE_READY,
}task_state_t;
typedef struct {
task_state_t state;
task_func_t *p_func;
jmp_buf env;
}task_t;
/**
* Global variables
*/
static jmp_buf root_env;
task_t *p_current_task = NULL;
task_t tasks[2];
/**
* Function declarations
*/
void task_root();
void task_init();
void task_add(task_func_t *p_func);
void task_yield();
task_t* task_search(task_func_t *p_func);
task_t* task_get_next();
void task_rerun(task_func_t *p_func);
/**
* Task functions (jobs)
*/
void task1(void);
void task2(void);
int main(void){
task_init();
task_add(&task1);
task_add(&task2);
task_root();
return 0;
}
/**
* Function definitions
*/
task_t* task_get_next(){
if (tasks[0].state == TASK_STATE_READY) {
return &tasks[0];
}else{
return &tasks[1];
}
}
void task_init(){
tasks[0].state = TASK_STATE_NONE;
tasks[1].state = TASK_STATE_NONE;
}
void task_yield(){
/* TASK YIELD */
// change the state of the task
printf("\ntask_yield running");
p_current_task->state = TASK_STATE_PAUSED;
if(!setjmp(p_current_task->env)){
longjmp(root_env, 1);
}
longjmp(p_current_task->env,1);
}
void task_root(){
printf("\ntask_root running");
setjmp(root_env);
p_current_task = task_get_next();
if (TASK_STATE_IDLE == p_current_task->state || TASK_STATE_READY == p_current_task->state) {
p_current_task->state = TASK_STATE_RUNNING;
p_current_task->p_func();
}else{
longjmp(p_current_task->env,1);
}
}
task_t* task_search(task_func_t *p_func){
if (tasks[0].p_func == p_func) {
return &tasks[0];
}else{
return &tasks[1];
}
}
void task_rerun(task_func_t *p_func){
task_t* p_task = task_search(p_func);
p_task->state = TASK_STATE_READY;
}
void task_add(task_func_t *p_func){
// listeye pointerları yerleştir
printf("\ntask_add()");
if (tasks[0].state == TASK_STATE_NONE) {
tasks[0].state = TASK_STATE_IDLE;
tasks[0].p_func = p_func;
}else if(tasks[1].state == TASK_STATE_NONE){
tasks[1].state = TASK_STATE_IDLE;
tasks[1].p_func = p_func;
}else{
printf("ERROR CANT ADD TASK!");
}
}
void task1(void){
while (1) {
// do sth
printf("\ntask_1()");
task_rerun(&task2);
task_yield();
}
}
void task2(void){
while (1) {
// do sth
printf("\ntask_2()");
task_rerun(&task1);
task_yield();
}
}