From 62cd4c87bcebf3ff16890bdac9b5994ada5c29e7 Mon Sep 17 00:00:00 2001 From: Elmer Bulthuis Date: Tue, 3 Dec 2019 15:08:38 +0100 Subject: [PATCH] sync middleware --- examples/light/stores.rs | 30 ++++++++++++++++++++++++++---- 1 file changed, 26 insertions(+), 4 deletions(-) diff --git a/examples/light/stores.rs b/examples/light/stores.rs index 261deac..5f04077 100644 --- a/examples/light/stores.rs +++ b/examples/light/stores.rs @@ -1,21 +1,26 @@ extern crate reduxr; use super::*; -use reduxr::*; +use reduxr::Store; +use std::sync::Mutex; pub fn create_store() -> Store { let store: Store = Store::default(); store.add_middleware(|next| { + let mutex = Mutex::new(()); + Box::new(move |store, action| { + next(store, action); + if let Action::Switch = action { + let _lock = mutex.lock(); let state = store.get_state(); if state.select_power() { store.dispatch(Action::TurnOff); } else { store.dispatch(Action::TurnOn); } - }; - next(store, action); + } }) }) } @@ -23,10 +28,12 @@ pub fn create_store() -> Store { #[cfg(test)] mod tests { use super::*; + use std::sync::Arc; #[test] fn test_store() { - let store = create_store(); + let store_arc = Arc::new(create_store()); + let store = store_arc.clone(); let state = store.get_state(); assert_eq!(state.select_power(), false); @@ -46,5 +53,20 @@ mod tests { store.dispatch(Action::Switch); let state = store.get_state(); assert_eq!(state.select_power(), false); + + for _ in 0..100 { + let threads: Vec<_> = (0..10) + .map(|_| store_arc.clone()) + .map(|store| std::thread::spawn(move || store.dispatch(Action::Switch))) + .collect(); + + threads + .into_iter() + .for_each(|thread| thread.join().unwrap()); + + let store = store_arc.clone(); + let state = store.get_state(); + assert_eq!(state.select_power(), false); + } } }