4 #include "libthreads.h"
8 /* global "model" struct */
11 #define STACK_SIZE (1024 * 1024)
13 static void *stack_allocate(size_t size)
18 static void stack_free(void *stack)
23 static int create_context(struct thread *t)
27 memset(&t->context, 0, sizeof(t->context));
28 ret = getcontext(&t->context);
32 /* t->start_routine == NULL means this is our initial context */
33 if (!t->start_routine)
36 /* Initialize new managed context */
37 t->stack = stack_allocate(STACK_SIZE);
38 t->context.uc_stack.ss_sp = t->stack;
39 t->context.uc_stack.ss_size = STACK_SIZE;
40 t->context.uc_stack.ss_flags = 0;
41 t->context.uc_link = &model->system_thread->context;
42 makecontext(&t->context, t->start_routine, 1, t->arg);
47 static int create_initial_thread(struct thread *t)
49 memset(t, 0, sizeof(*t));
50 return create_context(t);
53 static int thread_swap(struct thread *old, struct thread *new)
55 return swapcontext(&old->context, &new->context);
58 int thread_yield(void)
60 struct thread *old, *next;
63 old = thread_current();
64 model->scheduler->add_thread(old);
65 next = model->scheduler->next_thread();
66 DEBUG("(%d, %d)\n", old->index, next->index);
67 return thread_swap(old, next);
70 static void thread_dispose(struct thread *t)
72 DEBUG("completed thread %d\n", thread_current()->index);
73 t->state = THREAD_COMPLETED;
77 static void thread_wait_finish(void)
79 struct thread *curr, *next;
84 if ((curr = thread_current()))
86 next = model->scheduler->next_thread();
87 } while (next && !thread_swap(model->system_thread, next));
90 int thread_create(struct thread *t, void (*start_routine), void *arg)
92 static int created = 1;
97 memset(t, 0, sizeof(*t));
99 DEBUG("create thread %d\n", t->index);
101 t->start_routine = start_routine;
104 /* Initialize state */
105 ret = create_context(t);
109 t->state = THREAD_CREATED;
111 model->scheduler->add_thread(t);
115 void thread_join(struct thread *t)
117 while (t->state != THREAD_COMPLETED)
121 struct thread *thread_current(void)
123 return model->scheduler->get_current_thread();
128 struct thread user_thread;
129 struct thread *main_thread;
131 model_checker_init();
133 main_thread = malloc(sizeof(struct thread));
134 create_initial_thread(main_thread);
135 model_checker_add_system_thread(main_thread);
137 /* Start user program */
138 thread_create(&user_thread, &user_main, NULL);
140 /* Wait for all threads to complete */
141 thread_wait_finish();