7 #include "libthreads.h"
9 #define STACK_SIZE (1024 * 1024)
11 static struct thread *current;
13 static void *stack_allocate(size_t size)
18 static int create_context(struct thread *t)
22 memset(&t->context, 0, sizeof(t->context));
23 ret = getcontext(&t->context);
27 /* t->start_routine == NULL means this is our initial context */
28 if (!t->start_routine)
31 /* Initialize new managed context */
32 t->stack = stack_allocate(STACK_SIZE);
33 t->context.uc_stack.ss_sp = t->stack;
34 t->context.uc_stack.ss_size = STACK_SIZE;
35 t->context.uc_stack.ss_flags = 0;
36 t->context.uc_link = ¤t->context;
37 makecontext(&t->context, t->start_routine, 1, t->arg);
42 static int create_initial_thread(struct thread *t)
44 memset(t, 0, sizeof(*t));
45 return create_context(t);
48 int thread_create(struct thread *t, void (*start_routine), void *arg)
50 static int created = 1;
56 DEBUG("create thread %d\n", t->index);
58 t->start_routine = start_routine;
61 /* Initialize state */
62 return create_context(t);
65 void thread_start(struct thread *t)
67 struct thread *old = current;
71 swapcontext(&old->context, ¤t->context);
80 for (i = 0; i < 10; i++)
81 printf("Thread %d, loop %d\n", *idx, i);
89 thread_create(&t1, &a, &i);
90 thread_create(&t2, &a, &j);
92 printf("user_main() is going to start 2 threads\n");
95 printf("user_main() is finished\n");
100 struct thread main_thread, user_thread;
102 create_initial_thread(&main_thread);
103 current = &main_thread;
105 thread_create(&user_thread, &user_main, NULL);
107 thread_start(&user_thread);