1 /* -*- Mode: C; indent-tabs-mode: t -*- */
3 #include "libthreads.h"
7 /* global "model" object */
10 #define STACK_SIZE (1024 * 1024)
12 static void * stack_allocate(size_t size)
14 return userMalloc(size);
17 static void stack_free(void *stack)
22 Thread * thread_current(void)
24 return model->scheduler->get_current_thread();
27 /* This method just gets around makecontext not being 64-bit clean */
29 void thread_startup() {
30 Thread * curr_thread=thread_current();
31 curr_thread->start_routine(curr_thread->arg);
34 int Thread::create_context()
38 ret = getcontext(&context);
42 /* Initialize new managed context */
43 stack = stack_allocate(STACK_SIZE);
44 context.uc_stack.ss_sp = stack;
45 context.uc_stack.ss_size = STACK_SIZE;
46 context.uc_stack.ss_flags = 0;
47 context.uc_link = model->get_system_context();
48 makecontext(&context, start_routine, 1);
53 int Thread::swap(Thread *t, ucontext_t *ctxt)
55 return swapcontext(&t->context, ctxt);
58 int Thread::swap(ucontext_t *ctxt, Thread *t)
60 return swapcontext(ctxt, &t->context);
63 void Thread::complete()
65 if (state != THREAD_COMPLETED) {
66 DEBUG("completed thread %d\n", get_id());
67 state = THREAD_COMPLETED;
73 Thread::Thread(thrd_t *t, void (*func)(), void *a) {
80 /* Initialize state */
81 ret = create_context();
83 printf("Error in create_context\n");
85 state = THREAD_CREATED;
86 id = model->get_next_id();
88 parent = thread_current();
94 model->remove_thread(this);
97 thread_id_t Thread::get_id()