3 #include "libthreads.h"
8 /* global "model" object */
11 #define STACK_SIZE (1024 * 1024)
13 static void * stack_allocate(size_t size)
15 return userMalloc(size);
18 static void stack_free(void *stack)
23 Thread * thread_current(void)
25 return model->scheduler->get_current_thread();
28 int Thread::create_context()
32 ret = getcontext(&context);
36 /* start_routine == NULL means this is our initial context */
40 /* Initialize new managed context */
41 stack = stack_allocate(STACK_SIZE);
42 context.uc_stack.ss_sp = stack;
43 context.uc_stack.ss_size = STACK_SIZE;
44 context.uc_stack.ss_flags = 0;
45 context.uc_link = model->get_system_context();
46 makecontext(&context, start_routine, 1, arg);
51 int Thread::swap(Thread *t, ucontext_t *ctxt)
53 return swapcontext(&t->context, ctxt);
56 int Thread::swap(ucontext_t *ctxt, Thread *t)
58 return swapcontext(ctxt, &t->context);
61 void Thread::complete()
63 if (state != THREAD_COMPLETED) {
64 DEBUG("completed thread %d\n", get_id());
65 state = THREAD_COMPLETED;
71 void * Thread::operator new(size_t size) {
72 return userMalloc(size);
75 void Thread::operator delete(void *ptr) {
79 Thread::Thread(thrd_t *t, void (*func)(), void *a) {
86 /* Initialize state */
87 ret = create_context();
89 printf("Error in create_context\n");
91 state = THREAD_CREATED;
92 id = model->get_next_id();
96 Thread::Thread(thrd_t *t) {
104 state = THREAD_CREATED;
105 id = model->get_next_id();
107 model->set_system_context(&context);
113 model->remove_thread(this);
116 thread_id_t Thread::get_id()
122 * Return 1 if found next thread, 0 otherwise
124 static int thread_system_next(void)
128 curr = thread_current();
130 if (curr->get_state() == THREAD_READY) {
131 model->check_current_action();
132 model->scheduler->add_thread(curr);
133 } else if (curr->get_state() == THREAD_RUNNING)
134 /* Stopped while running; i.e., completed */
137 DEBUG("ERROR: current thread in unexpected state??\n");
139 next = model->scheduler->next_thread();
141 next->set_state(THREAD_RUNNING);
142 DEBUG("(%d, %d)\n", curr ? curr->get_id() : -1, next ? next->get_id() : -1);
145 return Thread::swap(model->get_system_context(), next);
148 static void thread_wait_finish(void)
153 while (!thread_system_next());
157 * Main system function
162 ucontext_t main_context;
164 model = new ModelChecker();
166 if (getcontext(&main_context))
169 model->set_system_context(&main_context);
172 /* Start user program */
173 thrd_create(&user_thread, &user_main, NULL);
175 /* Wait for all threads to complete */
176 thread_wait_finish();
177 } while (model->next_execution());