threads: add per-thread "return" values for 'model-checking/user context' switch
[c11tester.git] / threads.h
1 /** @file threads.h
2  *  @brief Model Checker Thread class.
3  */
4
5 #ifndef __THREADS_H__
6 #define __THREADS_H__
7
8 #include <ucontext.h>
9 #include "mymemory.h"
10 #include "libthreads.h"
11
12 typedef int thread_id_t;
13
14 #define THREAD_ID_T_NONE        -1
15
16 typedef enum thread_state {
17         THREAD_CREATED,
18         THREAD_RUNNING,
19         THREAD_READY,
20         THREAD_COMPLETED
21 } thread_state;
22
23 class ModelAction;
24
25 /** @brief A Thread is created for each user-space thread */
26 class Thread {
27 public:
28         Thread(thrd_t *t, void (*func)(void *), void *a);
29         ~Thread();
30         void complete();
31
32         static int swap(ucontext_t *ctxt, Thread *t);
33         static int swap(Thread *t, ucontext_t *ctxt);
34
35         thread_state get_state() { return state; }
36         void set_state(thread_state s) { state = s; }
37         thread_id_t get_id();
38         thrd_t get_thrd_t() { return *user_thread; }
39         Thread * get_parent() { return parent; }
40
41         void set_creation(ModelAction *act) { creation = act; }
42         ModelAction * get_creation() { return creation; }
43
44         /**
45          * Set a return value for the last action in this thread (e.g., for an
46          * atomic read).
47          * @param value The value to return
48          */
49         void set_return_value(int value) { last_action_val = value; }
50
51         /**
52          * Retrieve a return value for the last action in this thread. Used,
53          * for instance, for an atomic read to return the 'read' value. Should
54          * be called from a user context.
55          * @return The value 'returned' by the action
56          */
57         int get_return_value() { return last_action_val; }
58
59         friend void thread_startup();
60
61         SNAPSHOTALLOC
62 private:
63         int create_context();
64         Thread *parent;
65         ModelAction *creation;
66
67         void (*start_routine)(void *);
68         void *arg;
69         ucontext_t context;
70         void *stack;
71         thrd_t *user_thread;
72         thread_id_t id;
73         thread_state state;
74
75         /**
76          * The value returned by the last action in this thread
77          * @see Thread::set_return_value()
78          * @see Thread::get_return_value()
79          */
80         int last_action_val;
81 };
82
83 Thread * thread_current();
84
85 static inline thread_id_t thrd_to_id(thrd_t t)
86 {
87         return t;
88 }
89
90 static inline thread_id_t int_to_id(int i)
91 {
92         return i;
93 }
94
95 static inline int id_to_int(thread_id_t id)
96 {
97         return id;
98 }
99
100 #endif /* __THREADS_H__ */