From 5f953f76d8b62e6b8c8dd0a8fddc27e19410803c Mon Sep 17 00:00:00 2001 From: Paul Hauner Date: Fri, 25 Jan 2019 11:25:09 +1100 Subject: [PATCH] Make TestingSlotClock thread-safe --- eth2/utils/slot_clock/src/testing_slot_clock.rs | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/eth2/utils/slot_clock/src/testing_slot_clock.rs b/eth2/utils/slot_clock/src/testing_slot_clock.rs index de1d7ddb3..330d47f1a 100644 --- a/eth2/utils/slot_clock/src/testing_slot_clock.rs +++ b/eth2/utils/slot_clock/src/testing_slot_clock.rs @@ -1,11 +1,12 @@ use super::SlotClock; +use std::sync::RwLock; #[derive(Debug, PartialEq)] pub enum Error {} /// Determines the present slot based upon the present system time. pub struct TestingSlotClock { - slot: u64, + slot: RwLock, } impl TestingSlotClock { @@ -13,11 +14,13 @@ impl TestingSlotClock { /// /// Returns an Error if `slot_duration_seconds == 0`. pub fn new(slot: u64) -> TestingSlotClock { - TestingSlotClock { slot } + TestingSlotClock { + slot: RwLock::new(slot), + } } - pub fn set_slot(&mut self, slot: u64) { - self.slot = slot; + pub fn set_slot(&self, slot: u64) { + *self.slot.write().expect("TestingSlotClock poisoned.") = slot; } } @@ -25,7 +28,8 @@ impl SlotClock for TestingSlotClock { type Error = Error; fn present_slot(&self) -> Result, Error> { - Ok(Some(self.slot)) + let slot = *self.slot.read().expect("TestingSlotClock poisoned."); + Ok(Some(slot)) } } @@ -35,7 +39,7 @@ mod tests { #[test] fn test_slot_now() { - let mut clock = TestingSlotClock::new(10); + let clock = TestingSlotClock::new(10); assert_eq!(clock.present_slot(), Ok(Some(10))); clock.set_slot(123); assert_eq!(clock.present_slot(), Ok(Some(123)));