add support for pthread_mutex
[c11tester.git] / pthread.cc
1 #include "common.h"
2 #include "threads-model.h"
3 #include "action.h"
4 #include <pthread.h>
5 #include <mutex>
6 #include <vector>
7
8 /* global "model" object */
9 #include "model.h"
10
11 int pthread_create(pthread_t *t, const pthread_attr_t * attr,
12           pthread_start_t start_routine, void * arg) {
13         struct pthread_params params = { start_routine, arg };
14
15         ModelAction *act = new ModelAction(PTHREAD_CREATE, std::memory_order_seq_cst, t, (uint64_t)&params);
16         model->pthread_map[*t] = act;
17
18         /* seq_cst is just a 'don't care' parameter */
19         model->switch_to_master(act);
20
21         return 0;
22 }
23
24 int pthread_join(pthread_t t, void **value_ptr) {
25         ModelAction *act = model->pthread_map[t];
26         Thread *th = act->get_thread_operand();
27         model->switch_to_master(new ModelAction(PTHREAD_JOIN, std::memory_order_seq_cst, th, id_to_int(th->get_id())));
28         return 0;
29 }
30
31 void pthread_exit(void *value_ptr) {
32         Thread * th = thread_current();
33         model->switch_to_master(new ModelAction(THREAD_FINISH, std::memory_order_seq_cst, th));
34 }
35
36 int pthread_mutex_init(pthread_mutex_t *p_mutex, const pthread_mutexattr_t *) {
37         if (model->mutex_map.find(p_mutex) != model->mutex_map.end() /*&& table[p_mutex]->is_initialized()*/ ) {
38                 model_print("Reinitialize a lock\n");
39                 // return 1;    // 0 means success; 1 means failure
40         }
41
42         std::mutex *m = new std::mutex();
43         m->initialize();
44         model->mutex_map[p_mutex] = m;
45         return 0;
46 }
47
48 int pthread_mutex_lock(pthread_mutex_t *p_mutex) {
49         std::mutex *m = model->mutex_map[p_mutex];
50         m->lock();
51         /* error message? */
52         return 0;
53 }
54 int pthread_mutex_trylock(pthread_mutex_t *p_mutex) {
55         std::mutex *m = model->mutex_map[p_mutex];
56         return m->try_lock();
57         /* error message?  */
58 }
59 int pthread_mutex_unlock(pthread_mutex_t *p_mutex) {    
60         std::mutex *m = model->mutex_map[p_mutex];
61         m->unlock();
62         return 0;
63 }