merging stuff...made need to clean up some stuff...but need to push it somewhere...
[cdsspec-compiler.git] / threads.cc
1 #include "libthreads.h"
2 #include "common.h"
3 #include "threads.h"
4
5 /* global "model" object */
6 #include "model.h"
7
8 #define STACK_SIZE (1024 * 1024)
9
10 static void * stack_allocate(size_t size)
11 {
12         return userMalloc(size);
13 }
14
15 static void stack_free(void *stack)
16 {
17         userFree(stack);
18 }
19
20 Thread * thread_current(void)
21 {
22         return model->scheduler->get_current_thread();
23 }
24
25 int Thread::create_context()
26 {
27         int ret;
28
29         ret = getcontext(&context);
30         if (ret)
31                 return ret;
32
33         /* Initialize new managed context */
34         stack = stack_allocate(STACK_SIZE);
35         context.uc_stack.ss_sp = stack;
36         context.uc_stack.ss_size = STACK_SIZE;
37         context.uc_stack.ss_flags = 0;
38         context.uc_link = model->get_system_context();
39         makecontext(&context, start_routine, 1, arg);
40
41         return 0;
42 }
43
44 int Thread::swap(Thread *t, ucontext_t *ctxt)
45 {
46         return swapcontext(&t->context, ctxt);
47 }
48
49 int Thread::swap(ucontext_t *ctxt, Thread *t)
50 {
51         return swapcontext(ctxt, &t->context);
52 }
53
54 void Thread::complete()
55 {
56         if (state != THREAD_COMPLETED) {
57                 DEBUG("completed thread %d\n", get_id());
58                 state = THREAD_COMPLETED;
59                 if (stack)
60                         stack_free(stack);
61         }
62 }
63
64
65 Thread::Thread(thrd_t *t, void (*func)(), void *a) {
66         int ret;
67
68         user_thread = t;
69         start_routine = func;
70         arg = a;
71
72         /* Initialize state */
73         ret = create_context();
74         if (ret)
75                 printf("Error in create_context\n");
76
77         state = THREAD_CREATED;
78         id = model->get_next_id();
79         *user_thread = id;
80         parent = thread_current();
81 }
82
83 Thread::~Thread()
84 {
85         complete();
86         model->remove_thread(this);
87 }
88
89 thread_id_t Thread::get_id()
90 {
91         return id;
92 }