Skip to content

Commit 55fc005

Browse files
committed
Condvar: proper no threads implementation
This properly implements Condvar for a target that has no threads.
1 parent 4996052 commit 55fc005

File tree

1 file changed

+32
-7
lines changed

1 file changed

+32
-7
lines changed
Lines changed: 32 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,50 @@
1+
use crate::cell::RefCell;
12
use crate::sys::sync::Mutex;
3+
use crate::thread::sleep;
24
use crate::time::Duration;
35

4-
pub struct Condvar {}
6+
pub struct Condvar {
7+
value: RefCell<u32>,
8+
}
9+
10+
unsafe impl Send for Condvar {}
11+
unsafe impl Sync for Condvar {} // no threads on this platform
512

613
impl Condvar {
714
#[inline]
815
pub const fn new() -> Condvar {
9-
Condvar {}
16+
Condvar { value: RefCell::new(0) }
1017
}
1118

1219
#[inline]
13-
pub fn notify_one(&self) {}
20+
pub fn notify_one(&self) {
21+
*self.value.borrow_mut() += 1;
22+
}
1423

1524
#[inline]
16-
pub fn notify_all(&self) {}
25+
pub fn notify_all(&self) {
26+
*self.value.borrow_mut() += 1;
27+
}
1728

1829
pub unsafe fn wait(&self, _mutex: &Mutex) {
19-
panic!("condvar wait not supported")
30+
let mut value = self.value.borrow_mut();
31+
if *value == 0 {
32+
// Since the target does not have threads,
33+
// no notification can ever arrive.
34+
loop {}
35+
} else {
36+
*value -= 1;
37+
}
2038
}
2139

22-
pub unsafe fn wait_timeout(&self, _mutex: &Mutex, _dur: Duration) -> bool {
23-
panic!("condvar wait not supported");
40+
pub unsafe fn wait_timeout(&self, _mutex: &Mutex, dur: Duration) -> bool {
41+
let mut value = self.value.borrow_mut();
42+
if *value == 0 {
43+
sleep(dur);
44+
false
45+
} else {
46+
*value -= 1;
47+
true
48+
}
2449
}
2550
}

0 commit comments

Comments
 (0)