From c96915b4df869ace4373b5ff5b6de57d66ab07db Mon Sep 17 00:00:00 2001 From: Michael Mueller Date: Thu, 20 Jun 2019 08:24:57 +0200 Subject: [PATCH] Replace Mutex with RwLock --- src/module.rs | 2 +- src/not_threadsafe.rs | 3 ++- src/threadsafe.rs | 18 ++++++++++-------- 3 files changed, 13 insertions(+), 10 deletions(-) diff --git a/src/module.rs b/src/module.rs index b559006..8833438 100644 --- a/src/module.rs +++ b/src/module.rs @@ -213,7 +213,7 @@ impl ModuleInstance { /// Access all globals. This is a non-standard API so it's unlikely to be /// portable to other engines. - pub fn globals<'a>(&self) -> ::MyRef> { + pub fn globals<'a>(&self) -> ::MyRefRead> { self.globals.borrow() } diff --git a/src/not_threadsafe.rs b/src/not_threadsafe.rs index eed3b27..6719c96 100644 --- a/src/not_threadsafe.rs +++ b/src/not_threadsafe.rs @@ -1,5 +1,6 @@ pub use alloc::rc::Rc as MyRc; pub use alloc::rc::Weak as MyWeak; pub use core::cell::Cell as MyCell; -pub use core::cell::Ref as MyRef; +pub use core::cell::Ref as MyRefRead; +pub use core::cell::Ref as MyRefWrite; pub use core::cell::RefCell as MyRefCell; diff --git a/src/threadsafe.rs b/src/threadsafe.rs index 20b3cea..7d0316a 100644 --- a/src/threadsafe.rs +++ b/src/threadsafe.rs @@ -1,31 +1,33 @@ extern crate atomic; -use alloc::sync::{Arc, Mutex}; +use alloc::sync::{Arc, RwLock}; pub use self::atomic::{Atomic, Ordering::Relaxed as Ordering}; -pub use alloc::sync::{Arc as MyRc, MutexGuard as MyRef, Weak as MyWeak}; +pub use alloc::sync::{ + Arc as MyRc, RwLockReadGuard as MyRefRead, RwLockWriteGuard as MyRefWrite, Weak as MyWeak, +}; /// Thread-safe wrapper which can be used in place of a `RefCell`. #[derive(Debug)] -pub struct MyRefCell(Arc>); +pub struct MyRefCell(Arc>); impl MyRefCell { /// Create new wrapper object. pub fn new(obj: T) -> MyRefCell { - MyRefCell(Arc::new(Mutex::new(obj))) + MyRefCell(Arc::new(RwLock::new(obj))) } /// Borrow a `MyRef` to the inner value. - pub fn borrow(&self) -> ::MyRef { + pub fn borrow(&self) -> ::MyRefRead { self.0 - .lock() + .read() .expect("failed to acquire lock while trying to borrow") } /// Borrow a mutable `MyRef` to the inner value. - pub fn borrow_mut(&self) -> ::MyRef { + pub fn borrow_mut(&self) -> ::MyRefWrite { self.0 - .lock() + .write() .expect("failed to acquire lock while trying to borrow mutably") } }