-
Notifications
You must be signed in to change notification settings - Fork 0
/
gtthread_mutex.c
58 lines (47 loc) · 1.1 KB
/
gtthread_mutex.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#include "gtthread.h"
int gtthread_mutex_init(gtthread_mutex_t *mutex){
blockTimer();
if(mutex->mutex_lock == 1){
return -1;
}
mutex->mutex_lock = 0;
mutex->mutex_owner = current_context->thread_id;
unblockTimer();
return 0;
}
int gtthread_mutex_lock(gtthread_mutex_t *mutex){
blockTimer();
// Possibly reentrant lock
if(mutex->mutex_owner == current_context->thread_id && mutex->mutex_lock==1){
unblockTimer();
return 0;
}
// Wait till the lock is free
while(mutex->mutex_lock == 1 && mutex->mutex_owner != current_context->thread_id){
unblockTimer();
gtthread_yield();
blockTimer();
};
mutex->mutex_lock = 1;
mutex->mutex_owner = current_context->thread_id;
unblockTimer();
return 0;
}
int gtthread_mutex_unlock(gtthread_mutex_t *mutex){
blockTimer();
if(mutex->mutex_owner != current_context->thread_id){
unblockTimer();
return -1;
}
// if(mutex->mutex_owner == )
mutex->mutex_lock = 0;
mutex->mutex_owner = -1;
unblockTimer();
return 0;
}
int gtthread_mutex_destroy(gtthread_mutex_t *mutex){
blockTimer();
mutex->mutex_owner=-1;
mutex->mutex_lock = 0;
return 0;
}