From cb4f82b2a9f9099e8a460d5207f14deba41e4588 Mon Sep 17 00:00:00 2001 From: WangRunji Date: Fri, 1 Jun 2018 16:45:22 +0800 Subject: [PATCH] Extract Condvar from ThreadLock --- src/sync/condvar.rs | 27 +++++++++++++++++++++++++++ src/sync/mod.rs | 6 ++++-- src/sync/mutex.rs | 19 ++++++------------- 3 files changed, 37 insertions(+), 15 deletions(-) create mode 100644 src/sync/condvar.rs diff --git a/src/sync/condvar.rs b/src/sync/condvar.rs new file mode 100644 index 0000000..9154a3f --- /dev/null +++ b/src/sync/condvar.rs @@ -0,0 +1,27 @@ +use thread; +use alloc::VecDeque; +use super::SpinNoIrqLock; + +pub struct Condvar { + wait_queue: SpinNoIrqLock>, +} + +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(); + } + } +} \ No newline at end of file diff --git a/src/sync/mod.rs b/src/sync/mod.rs index 0b880ac..f9e469a 100644 --- a/src/sync/mod.rs +++ b/src/sync/mod.rs @@ -1,5 +1,7 @@ mod mutex; -mod semaphore; +mod condvar; +//mod semaphore; pub mod test; -pub use self::mutex::*; \ No newline at end of file +pub use self::mutex::*; +pub use self::condvar::*; \ No newline at end of file diff --git a/src/sync/mutex.rs b/src/sync/mutex.rs index 5660b3c..9b8c00f 100644 --- a/src/sync/mutex.rs +++ b/src/sync/mutex.rs @@ -33,7 +33,7 @@ use core::fmt; pub type SpinLock = Mutex; pub type SpinNoIrqLock = Mutex; -pub type ThreadLock = Mutex; +pub type ThreadLock = Mutex; pub struct Mutex { @@ -253,25 +253,18 @@ impl MutexSupport for SpinNoIrq { use thread; use alloc::VecDeque; +use super::Condvar; -/// With thread support -pub struct Thread { - wait_queue: SpinLock>, -} - -impl MutexSupport for Thread { +impl MutexSupport for Condvar { type GuardData = (); fn new() -> Self { - Thread { wait_queue: SpinLock::new(VecDeque::new()) } + Condvar::new() } fn cpu_relax(&self) { - self.wait_queue.lock().push_back(thread::current()); - thread::park(); + self.wait(); } fn before_lock() -> Self::GuardData {} fn after_unlock(&self) { - if let Some(t) = self.wait_queue.lock().pop_front() { - t.unpark(); - } + self.notify_one(); } } \ No newline at end of file