Skip to content

Instantly share code, notes, and snippets.

@chanmix51
Created September 4, 2024 09:15
Show Gist options
  • Save chanmix51/d771a43ae8ed71a890492e6b6a5a1cbd to your computer and use it in GitHub Desktop.
Save chanmix51/d771a43ae8ed71a890492e6b6a5a1cbd to your computer and use it in GitHub Desktop.
Sharing a buffer with a Thread and test it afterward.
use std::error::Error;
use std::io::{Cursor, Write};
use std::sync::{Arc, Mutex};
use std::thread;
struct Actor {
buffer: Arc<Mutex<dyn Write + Sync + Send>>
}
/// This Actor does write in the given Buffer (StdOut, File, …)
impl Actor {
pub fn new(buffer: Arc<Mutex<dyn Write + Sync + Send>>) -> Self {
Self { buffer }
}
pub fn run(self) -> Result<(), Box<dyn Error + Sync + Send>> {
let data = b"This is some real data";
let mut buffer = self.buffer.lock().unwrap();
buffer.write(data)?;
Ok(())
}
}
fn main() -> Result<(), String> {
let buffer: Arc<Mutex<Cursor<Vec<u8>>>> = Arc::new(Mutex::new(Cursor::new(Vec::new())));
let actor = Actor::new(buffer.clone());
let thread = thread::spawn(move || { actor.run() });
thread.join().unwrap().expect("Buffer must have been written correctly.");
let bytes = Arc::into_inner(buffer) // consume Arc
.expect("there should not be any other copy of this Arc")
.into_inner()
.expect("Mutex is poisoned?")
.into_inner(); // consume the Cursor
let message = String::from_utf8(bytes).unwrap();
assert_eq!("This is some real data", &message);
Ok(())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment