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 old->state = THREAD_READY;
65 next = model->system_thread;
66 return thread_swap(old, next);
69 static void thread_dispose(struct thread *t)
71 DEBUG("completed thread %d\n", thread_current()->index);
72 t->state = THREAD_COMPLETED;
77 * Return 1 if found next thread, 0 otherwise
79 static int thread_system_next(void)
81 struct thread *curr, *next;
83 curr = thread_current();
85 if (curr->state == THREAD_READY)
86 model->scheduler->add_thread(curr);
87 else if (curr->state == THREAD_RUNNING)
88 /* Stopped while running; i.e., completed */
91 DEBUG("ERROR: current thread in unexpected state??\n");
93 next = model->scheduler->next_thread();
95 next->state = THREAD_RUNNING;
96 DEBUG("(%d, %d)\n", curr ? curr->index : -1, next ? next->index : -1);
99 return thread_swap(model->system_thread, next);
102 static void thread_wait_finish(void)
107 while (!thread_system_next());
110 int thread_create(struct thread *t, void (*start_routine), void *arg)
112 static int created = 1;
117 memset(t, 0, sizeof(*t));
118 t->index = created++;
119 DEBUG("create thread %d\n", t->index);
121 t->start_routine = start_routine;
124 /* Initialize state */
125 ret = create_context(t);
129 t->state = THREAD_CREATED;
131 model->scheduler->add_thread(t);
135 void thread_join(struct thread *t)
137 while (t->state != THREAD_COMPLETED)
141 struct thread *thread_current(void)
143 return model->scheduler->get_current_thread();
148 struct thread user_thread;
149 struct thread *main_thread;
151 model_checker_init();
153 main_thread = malloc(sizeof(struct thread));
154 create_initial_thread(main_thread);
155 model_checker_add_system_thread(main_thread);
157 /* Start user program */
158 thread_create(&user_thread, &user_main, NULL);
160 /* Wait for all threads to complete */
161 thread_wait_finish();