-
Notifications
You must be signed in to change notification settings - Fork 0
/
syncro.c
121 lines (109 loc) · 2.2 KB
/
syncro.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
#include "syncro.h"
#include <avr/interrupt.h>
void mutex_init(mutex_t* m)
{
int i;
cli();
m->value = 1;
for(i; i < MAX_THREADS; i++)
m->waitlist[i] = 0;
sei();
}
void mutex_lock(mutex_t* m)
{
cli();
//Lock is not currently held
if(m->value == 1)
m->value--;
//Lock is held
else
{
m->waitlist[getCurrentThread()] = 1;
blocked();
}
sei();
}
void mutex_unlock(mutex_t* m)
{
cli();
int i;
if(!m->value)
{
m->value = 1;
//Make sure we have no one waiting on us
//This biases early threads
for(i; i < MAX_THREADS; i++)
{
if(m->waitlist[i])
{
m->waitlist[i] = 0;
setThreadState(i, THREAD_READY);
break;
}
}
}
sei();
}
void sem_init(semaphore_t* s, int8_t value)
{
cli();
int i;
s->value = value;
for(i; i < MAX_THREADS; i++)
s->waitlist[i] = 0;
sei();
}
void sem_wait(semaphore_t* s)
{
cli();
//Semaphore unavailable
if(--s->value < 0)
{
s->waitlist[getCurrentThread()] = 1;
setThreadState(getCurrentThread(), THREAD_WAITING);
threadSwap(get_next_thread(), getCurrentThread());
}
sei();
}
void sem_signal(semaphore_t* s)
{
cli();
int i;
//Make sure we have no one waiting on us
//This biases early threads
if(++s->value <= 0)
{
for(i; i < MAX_THREADS; i++)
{
if(s->waitlist[i])
{
s->waitlist[i] = 0;
setThreadState(i, THREAD_READY);
break;
}
}
}
sei();
}
void sem_signal_swap(semaphore_t* s)
{
cli();
int i;
//Make sure we have no one waiting on us
//This biases early threads
if(++s->value <= 0)
{
for(i; i < MAX_THREADS; i++)
{
if(s->waitlist[i])
{
s->waitlist[i] = 0;
setThreadState(i, THREAD_RUNNING);
setThreadState(getCurrentThread(), THREAD_READY);
threadSwap(i, getCurrentThread());
break;
}
}
}
sei();
}