Skip to content

Instantly share code, notes, and snippets.

@0x5d
Last active March 28, 2018 03:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 0x5d/29f92e42ba336544cefb5f02622866af to your computer and use it in GitHub Desktop.
Save 0x5d/29f92e42ba336544cefb5f02622866af to your computer and use it in GitHub Desktop.
use std::io;
use std::sync::{Arc, LockResult, RwLock, RwLockReadGuard};
use std::thread::{Builder, JoinHandle};
struct Thing {
xs: RwLock<Vec<String>>
}
impl Thing {
fn new() -> Thing {
Thing {
xs: RwLock::new(Vec::new()),
}
}
fn start(&self) -> io::Result<JoinHandle<()>> {
let self1 = Arc::new(self);
let self2 = self1.clone();
Builder::new()
.name("thread1".to_owned())
.spawn(move || loop {
self1.do_within_thread1();
});
let result = Builder::new()
.name("thread2".to_owned())
.spawn(move || loop {
self2.do_within_thread2();
});
return result;
}
fn get_xs(&self) -> LockResult<RwLockReadGuard<Vec<String>>> {
return self.xs.read();
}
fn do_within_thread1(&self) {
// read and potentially mutate self.xs
}
fn do_within_thread2(&self) {
// read and potentially mutate self.xs
}
}
fn main() {
let thing = Thing::new();
let handle = match thing.start() {
Ok(handle) => handle,
_ => panic!("Error"),
};
thing.get_xs();
handle.join();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment