2 * @brief Thread functions.
5 #include "libthreads.h"
9 /* global "model" object */
12 /** Allocate a stack for a new thread. */
13 static void * stack_allocate(size_t size)
18 /** Free a stack for a terminated thread. */
19 static void stack_free(void *stack)
24 /** Return the currently executing thread. */
26 Thread * thread_current(void)
29 return model->scheduler->get_current_thread();
33 * Provides a startup wrapper for each thread, allowing some initial
34 * model-checking data to be recorded. This method also gets around makecontext
35 * not being 64-bit clean
36 * @todo We should make the START event always immediately follow the
37 * CREATE event, so we don't get redundant traces...
40 void thread_startup() {
41 Thread * curr_thread = thread_current();
43 /* Add dummy "start" action, just to create a first clock vector */
44 model->switch_to_master(new ModelAction(THREAD_START, std::memory_order_seq_cst, curr_thread));
46 /* Call the actual thread function */
47 curr_thread->start_routine(curr_thread->arg);
50 /** Create a thread context for a new thread so we can use
51 * setcontext/getcontext/swapcontext to swap it out.
52 * @return 0 on success.
55 int Thread::create_context()
59 ret = getcontext(&context);
63 /* Initialize new managed context */
64 stack = stack_allocate(STACK_SIZE);
65 context.uc_stack.ss_sp = stack;
66 context.uc_stack.ss_size = STACK_SIZE;
67 context.uc_stack.ss_flags = 0;
68 context.uc_link = model->get_system_context();
69 makecontext(&context, thread_startup, 0);
74 int Thread::swap(Thread *t, ucontext_t *ctxt)
76 return swapcontext(&t->context, ctxt);
79 int Thread::swap(ucontext_t *ctxt, Thread *t)
81 return swapcontext(ctxt, &t->context);
85 /** Terminate a thread and free its stack. */
87 void Thread::complete()
89 if (state != THREAD_COMPLETED) {
90 DEBUG("completed thread %d\n", get_id());
91 state = THREAD_COMPLETED;
97 /** Create a new thread.
98 * Takes the following parameters:
99 * @param t The thread identifier of the newly created thread.
100 * @param func The function that the thread will call.
101 * @param a The parameter to pass to this function. */
103 Thread::Thread(thrd_t *t, void (*func)(void *), void *a) :
107 state(THREAD_CREATED),
108 last_action_val(VALUE_NONE)
112 /* Initialize state */
113 ret = create_context();
115 printf("Error in create_context\n");
117 id = model->get_next_id();
119 parent = thread_current();
125 model->remove_thread(this);
128 /** Return the thread_id_t corresponding to this Thread object. */
130 thread_id_t Thread::get_id()