Extract Condvar from ThreadLock

master
WangRunji 7 years ago
parent 5891613b22
commit cb4f82b2a9

@ -0,0 +1,27 @@
use thread;
use alloc::VecDeque;
use super::SpinNoIrqLock;
pub struct Condvar {
wait_queue: SpinNoIrqLock<VecDeque<thread::Thread>>,
}
impl Condvar {
pub fn new() -> Self {
Condvar { wait_queue: SpinNoIrqLock::new(VecDeque::new()) }
}
pub fn wait(&self) {
self.wait_queue.lock().push_back(thread::current());
thread::park();
}
pub fn notify_one(&self) {
if let Some(t) = self.wait_queue.lock().pop_front() {
t.unpark();
}
}
pub fn notify_all(&self) {
while let Some(t) = self.wait_queue.lock().pop_front() {
t.unpark();
}
}
}

@ -1,5 +1,7 @@
mod mutex; mod mutex;
mod semaphore; mod condvar;
//mod semaphore;
pub mod test; pub mod test;
pub use self::mutex::*; pub use self::mutex::*;
pub use self::condvar::*;

@ -33,7 +33,7 @@ use core::fmt;
pub type SpinLock<T> = Mutex<T, Spin>; pub type SpinLock<T> = Mutex<T, Spin>;
pub type SpinNoIrqLock<T> = Mutex<T, SpinNoIrq>; pub type SpinNoIrqLock<T> = Mutex<T, SpinNoIrq>;
pub type ThreadLock<T> = Mutex<T, Thread>; pub type ThreadLock<T> = Mutex<T, Condvar>;
pub struct Mutex<T: ?Sized, S: MutexSupport> pub struct Mutex<T: ?Sized, S: MutexSupport>
{ {
@ -253,25 +253,18 @@ impl MutexSupport for SpinNoIrq {
use thread; use thread;
use alloc::VecDeque; use alloc::VecDeque;
use super::Condvar;
/// With thread support impl MutexSupport for Condvar {
pub struct Thread {
wait_queue: SpinLock<VecDeque<thread::Thread>>,
}
impl MutexSupport for Thread {
type GuardData = (); type GuardData = ();
fn new() -> Self { fn new() -> Self {
Thread { wait_queue: SpinLock::new(VecDeque::new()) } Condvar::new()
} }
fn cpu_relax(&self) { fn cpu_relax(&self) {
self.wait_queue.lock().push_back(thread::current()); self.wait();
thread::park();
} }
fn before_lock() -> Self::GuardData {} fn before_lock() -> Self::GuardData {}
fn after_unlock(&self) { fn after_unlock(&self) {
if let Some(t) = self.wait_queue.lock().pop_front() { self.notify_one();
t.unpark();
}
} }
} }
Loading…
Cancel
Save