blob: ccc7767ccb96d38519871a233b075e298a49de54 (
plain)
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
|
/**
* @file cond.c
* @author Hanjie Wu (hanjiew)
* @author Devang Acharya (devanga)
* @brief
* @date 2023-02-22
*
*/
#include <assert.h>
#include <cond.h>
#include <stdlib.h>
#include <syscall.h>
/**
* @brief initialize the condition variable pointed by cv
*
* @param cv
* @return 0
*/
int cond_init(cond_t* cv) {
mutex_init(&cv->lock);
cv->queue = NULL;
return 0;
}
/**
* @brief destroy the condition variable pointed by cv.
*
* @param cv
*/
void cond_destroy(cond_t* cv) {
affirm(cv->queue == NULL);
mutex_destroy(&cv->lock);
}
/**
* @brief wait on a cv until signaled and lock mp
*
* @param cv
*/
void cond_wait(cond_t* cv, mutex_t* mp) {
cond_node_t self;
mutex_lock(&cv->lock);
self.tid = gettid();
self.signaled = 0;
if (cv->queue == NULL) { /* add self node to wait list */
cv->queue = &self;
self.next = self.prev = &self;
} else {
self.next = cv->queue;
self.prev = cv->queue->prev;
cv->queue->prev->next = &self;
cv->queue->prev = &self;
}
mutex_unlock(mp);
mutex_unlock(&cv->lock);
while (self.signaled != 1) {
deschedule(&self.signaled); /* will be set to 1 after other thread
signal the cv */
}
mutex_lock(mp);
}
/**
* @brief signal a cv and wake up one thread
*
* @param cv
*/
void cond_signal(cond_t* cv) {
mutex_lock(&cv->lock);
if (cv->queue != NULL) { /* remove a waiter from the list */
cond_node_t* p = cv->queue;
if (p->next == p) {
cv->queue = NULL;
} else {
cv->queue = p->next;
p->next->prev = p->prev;
p->prev->next = p->next;
}
int tid = p->tid;
p->signaled = 1;
make_runnable(tid);
}
mutex_unlock(&cv->lock);
}
/**
* @brief signal a cv and wake up all threads
*
* @param cv
*/
void cond_broadcast(cond_t* cv) {
mutex_lock(&cv->lock);
cond_node_t* p = cv->queue;
if (p != NULL) {
cond_node_t* end = p;
do {
cond_node_t* q = p->next;
int tid = p->tid;
p->signaled = 1;
make_runnable(tid);
p = q;
} while (p != end);
cv->queue = NULL;
}
mutex_unlock(&cv->lock);
}
|