6 #include "libthreads.h"
8 #define STACK_SIZE (1024 * 1024)
10 static struct thread *current;
12 static void *stack_allocate(size_t size)
17 static int create_context(struct thread *t)
21 memset(&t->context, 0, sizeof(t->context));
22 ret = getcontext(&t->context);
26 /* t->start_routine == NULL means this is our initial context */
27 if (!t->start_routine)
30 /* Initialize new managed context */
31 t->stack = stack_allocate(STACK_SIZE);
32 t->context.uc_stack.ss_sp = t->stack;
33 t->context.uc_stack.ss_size = STACK_SIZE;
34 t->context.uc_stack.ss_flags = 0;
35 t->context.uc_link = ¤t->context;
36 makecontext(&t->context, t->start_routine, 1, t->arg);
41 static int create_initial_thread(struct thread *t)
43 memset(t, 0, sizeof(*t));
44 return create_context(t);
47 int thread_create(struct thread *t, void (*start_routine), void *arg)
49 static int created = 1;
53 memset(t, 0, sizeof(*t));
55 DEBUG("create thread %d\n", t->index);
57 t->start_routine = start_routine;
60 /* Initialize state */
61 return create_context(t);
64 void thread_start(struct thread *t)
66 struct thread *old = current;
70 swapcontext(&old->context, ¤t->context);
79 for (i = 0; i < 10; i++)
80 printf("Thread %d, loop %d\n", *idx, i);
88 thread_create(&t1, &a, &i);
89 thread_create(&t2, &a, &j);
91 printf("%s() is going to start 1 thread\n", __func__);
94 printf("%s() is finished\n", __func__);
99 struct thread main_thread, user_thread;
101 create_initial_thread(&main_thread);
102 current = &main_thread;
104 thread_create(&user_thread, &user_main, NULL);
105 thread_start(&user_thread);