-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcond.c
68 lines (52 loc) · 1.3 KB
/
cond.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
#include <avr/interrupt.h>
#include "cond.h"
void cond_init(cond_t *c) {
QUEUE_INIT(&c->waiting);
}
// Assume the mutex is held by the caller.
// It is too expensive to do run-time integrity checks on this processor.
void cond_wait(cond_t *c, mutex_t *m) {
uint8_t sreg;
sreg = SREG;
cli();
// Unlocking and suspending must happen atomically.
// If it doesn't, a race could cause a cond_{signal,broadcast} from another
// task holding the lock before this task has been suspended.
mutex_unlock(m);
// Suspend task until woken up through cond_{signal,broadcast}.
task_suspend(&c->waiting);
// Task may be interrupted again.
SREG = sreg;
// Reacquire mutex.
mutex_lock(m);
}
void cond_signal(cond_t *c) {
uint8_t sreg;
QUEUE *q;
task_t *t;
sreg = SREG;
cli();
// Wake up first waiting task (FIFO order).
if (!QUEUE_EMPTY(&c->waiting)) {
q = QUEUE_HEAD(&c->waiting);
t = QUEUE_DATA(q, task_t, member);
QUEUE_REMOVE(q);
task_wakeup(t);
}
SREG = sreg;
}
void cond_broadcast(cond_t *c) {
uint8_t sreg;
QUEUE *q;
task_t *t;
sreg = SREG;
cli();
// Wake up all waiting tasks.
while (!QUEUE_EMPTY(&c->waiting)) {
q = QUEUE_HEAD(&c->waiting);
t = QUEUE_DATA(q, task_t, member);
QUEUE_REMOVE(q);
task_wakeup(t);
}
SREG = sreg;
}