Created
September 30, 2015 00:41
-
-
Save lpereira/dacb529ccf730e4e69d6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdbool.h> | |
#include <stdlib.h> | |
struct task { | |
void *(*cb)(void *data); | |
void *data; | |
bool runnable; | |
}; | |
struct scheduler { | |
struct task *tasks; | |
int current_task; | |
}; | |
struct fib_state { | |
int a, b; | |
}; | |
struct inc_state { | |
int cur; | |
}; | |
void scheduler_schedule(struct scheduler *s) | |
{ | |
struct task *current = &s->tasks[s->current_task]; | |
if (!current->cb) { | |
s->current_task = 0; | |
return; | |
} | |
if (current->runnable) { | |
void *data = current->cb(current->data); | |
if (data) { | |
current->data = data; | |
} else { | |
printf("Ending task %d\n", s->current_task); | |
free(current->data); | |
current->runnable = false; | |
} | |
} | |
s->current_task++; | |
} | |
void *fibonacci(void *d) | |
{ | |
struct fib_state *s = d; | |
int c; | |
if (!d) { | |
s = malloc(sizeof(*s)); | |
if (!s) abort(); | |
s->a = s->b = 1; | |
} else { | |
printf("fib: %d\n", s->a); | |
c = s->a + s->b; | |
s->a = s->b; | |
s->b = c; | |
} | |
return s; | |
} | |
void *incrementa(void *d) | |
{ | |
struct inc_state *s = d; | |
if (!d) { | |
s = malloc(sizeof(*s)); | |
if (!s) abort(); | |
s->cur = 0; | |
} else if (s->cur < 100) { | |
printf("inc: %d\n", s->cur); | |
s->cur++; | |
} else { | |
return NULL; | |
} | |
return s; | |
} | |
int main(void) | |
{ | |
struct scheduler scheduler = { | |
.tasks = (struct task[]) { | |
{ .cb = fibonacci, .data = NULL, .runnable = true }, | |
{ .cb = incrementa, .data = NULL, .runnable = true }, | |
{ } | |
}, | |
.current_task = 0 | |
}; | |
while (true) { | |
scheduler_schedule(&scheduler); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment