Skip to content

Instantly share code, notes, and snippets.

@veryjos
Created February 6, 2019 01:41
Show Gist options
  • Save veryjos/3de1c3b02fb7fc33599c81346e5b9437 to your computer and use it in GitHub Desktop.
Save veryjos/3de1c3b02fb7fc33599c81346e5b9437 to your computer and use it in GitHub Desktop.
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