Repository navigation
Expand file tree
/
Copy pathsleep_cpu_std.rs
More file actions
73 lines (55 loc) · 1.9 KB
/
Copy pathsleep_cpu_std.rs
File metadata and controls
73 lines (55 loc) · 1.9 KB
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
use super::{SleepCpu, NUM_MAX_CPU};
use array_macro::array;
use core::time::Duration;
#[derive(Debug, Clone, Copy)]
struct SleepState {
is_awake: bool,
is_wake_up: bool,
}
static MUTEX_COND: [(std::sync::Mutex<SleepState>, std::sync::Condvar); NUM_MAX_CPU - 1] = array![_ => (std::sync::Mutex::new(SleepState{is_awake: true, is_wake_up: false}), std::sync::Condvar::new()); NUM_MAX_CPU - 1];
pub(super) struct SleepCpuStd;
impl SleepCpu for SleepCpuStd {
fn sleep(&self, timeout: Option<Duration>) {
// SleepCpuStd::sleep() does not support timeout.
assert!(timeout.is_none());
let cpu_id = super::cpu_id();
// The primary CPU uses epoll/select to wait for events.
// So, it must not use `sleep()`.
assert!(cpu_id > 0);
let (mtx, condvar) = &MUTEX_COND[cpu_id - 1];
let mut guard = mtx.lock().expect("Error: Failed to lock mutex.");
if guard.is_wake_up {
return;
}
guard.is_awake = false;
// In case that there are any tasks to run,
// wake up the primary CPU to wake me up.
crate::select::notify();
loop {
guard = condvar
.wait(guard)
.expect("Error: Failed to wait on condvar.");
if guard.is_wake_up {
guard.is_awake = true;
guard.is_wake_up = false;
break;
}
// Spurious wake up.
}
}
fn wake_up(cpu_id: usize) -> bool {
if cpu_id == 0 {
crate::select::notify();
return true;
}
let (mtx, condvar) = &MUTEX_COND[cpu_id - 1];
let mut guard = mtx.lock().expect("Error: Failed to lock mutex.");
if guard.is_awake {
// The CPU is already awake.
return false;
}
guard.is_wake_up = true;
condvar.notify_one();
true
}
}