-
-
Save veryjos/3de1c3b02fb7fc33599c81346e5b9437 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::marker::Send; | |
use std::sync::atomic::AtomicPtr; | |
/// Size of the buffer used for the underlying circular buffer. | |
const BUFFER_SIZE: usize = 16; | |
/// A cell which is syncronized across threads. | |
/// | |
/// When a reader requests the data held by this cell, the most recently | |
/// written data will be given to the reader. | |
pub struct SyncCell<T: Copy> { | |
current: usize, | |
last_update: AtomicPtr<T>, | |
buffer: [T; BUFFER_SIZE] | |
} | |
impl<T: Copy> SyncCell<T> { | |
/// Updates the data in the cell. | |
pub fn update(&mut self, data: T) { | |
self.current = (self.current + 1) % BUFFER_SIZE; | |
self.buffer[self.current] = data; | |
unsafe { | |
self.last_update = self.buffer.as_mut_ptr().add(self.current).into(); | |
} | |
} | |
/// Reads the most recently available data from the cell. | |
pub fn read(&mut self) -> T { | |
unsafe { **self.last_update.get_mut() } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment