Skip to content

Instantly share code, notes, and snippets.

@mpdavis
Created October 28, 2013 00:41
Show Gist options
  • Save mpdavis/7189689 to your computer and use it in GitHub Desktop.
Save mpdavis/7189689 to your computer and use it in GitHub Desktop.
#define _XOPEN_SOURCE 600
#include <ucontext.h>
#include <stdlib.h>
/*** Globals ***/
#define THREAD_ARRAY_SIZE 100
static int max_klt;
static int current_klt;
static ucontext_t* ctx[THREAD_ARRAY_SIZE];
static int pos;
static int running_pos;
/*** Functions ***/
void system_init(int max_number_of_klt){
max_klt = max_number_of_klt;
current_klt = 0;
pos = 0;
running_pos = -1;
}
int uthread_create(void func()){
if(pos < THREAD_ARRAY_SIZE){
ctx[pos] = malloc(sizeof(ucontext_t));
getcontext(ctx[pos]);
//Allocate memory for the context stack
ctx[pos]->uc_stack.ss_sp = malloc(16384);
ctx[pos]->uc_stack.ss_size = 16384;
makecontext(ctx[pos], func, 0);
pos++;
if(current_klt < max_klt){
void *child_stack;
child_stack = (void *)malloc(16384);
clone(func, child_stack, 0, NULL);
running_pos = -1;
current_klt++;
}
return 0;
}
return -1;
}
int uthread_yield(){
if(running_pos >= 0 && running_pos < pos){
setcontext(ctx[running_pos + 1]);
running_pos++;
return 0;
}
return -1;
}
void uthread_exit(){
if(running_pos >= 0 && running_pos < pos){
setcontext(ctx[running_pos + 1]);
running_pos++;
}
else{
exit(running_pos);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment