7 #include "libthreads.h"
9 #define STACK_SIZE (1024 * 1024)
11 static struct thread *current;
12 static ucontext_t *cleanup;
14 static void *stack_allocate(size_t size)
19 int thread_create(struct thread *t, void (*start_routine), void *arg)
27 DEBUG("create thread %d\n", t->index);
29 t->start_routine = start_routine;
32 /* Initialize state */
33 getcontext(&t->context);
34 t->stack = stack_allocate(STACK_SIZE);
35 t->context.uc_stack.ss_sp = t->stack;
36 t->context.uc_stack.ss_size = STACK_SIZE;
37 t->context.uc_stack.ss_flags = 0;
39 t->context.uc_link = ¤t->context;
41 t->context.uc_link = cleanup;
42 makecontext(&t->context, t->start_routine, 1, t->arg);
47 void thread_start(struct thread *t)
52 struct thread *old = current;
54 swapcontext(&old->context, ¤t->context);
57 swapcontext(cleanup, ¤t->context);
66 for (i = 0; i < 10; i++)
67 printf("Thread %d, loop %d\n", *idx, i);
75 thread_create(&t1, &a, &i);
76 thread_create(&t2, &a, &j);
78 printf("user_main() is going to start 2 threads\n");
81 printf("user_main() is finished\n");
87 ucontext_t main_context;
89 cleanup = &main_context;
91 thread_create(&t, &user_main, NULL);