9 #define DBG() do { printf("Here: %s, L%d\n", __func__, __LINE__); } while (0)
10 #define DEBUG(fmt, ...) printf(fmt, ##__VA_ARGS__)
13 #define DEBUG(fmt, ...)
16 #define STACK_SIZE (1024 * 1024)
19 void (*start_routine);
26 static struct thread *current;
27 static ucontext_t *cleanup;
29 static void *stack_allocate(size_t size)
34 int thread_create(struct thread *t, void (*start_routine), void *arg)
42 DEBUG("create thread %d\n", t->index);
44 t->start_routine = start_routine;
47 /* Initialize state */
48 getcontext(&t->context);
49 t->stack = stack_allocate(STACK_SIZE);
50 t->context.uc_stack.ss_sp = t->stack;
51 t->context.uc_stack.ss_size = STACK_SIZE;
52 t->context.uc_stack.ss_flags = 0;
54 t->context.uc_link = ¤t->context;
56 t->context.uc_link = cleanup;
57 makecontext(&t->context, t->start_routine, 1, t->arg);
62 void thread_start(struct thread *t)
67 struct thread *old = current;
69 swapcontext(&old->context, ¤t->context);
72 swapcontext(cleanup, ¤t->context);
81 for (i = 0; i < 10; i++)
82 printf("Thread %d, loop %d\n", *idx, i);
90 thread_create(&t1, &a, &i);
91 thread_create(&t2, &a, &j);
93 printf("user_main() is going to start 2 threads\n");
96 printf("user_main() is finished\n");
102 ucontext_t main_context;
104 cleanup = &main_context;
106 thread_create(&t, &user_main, NULL);