Skip to content

Instantly share code, notes, and snippets.

@kennykerr
Last active October 28, 2024 19:51
Show Gist options
  • Save kennykerr/68b66da6e3f1b31a1253e3d920019e31 to your computer and use it in GitHub Desktop.
Save kennykerr/68b66da6e3f1b31a1253e3d920019e31 to your computer and use it in GitHub Desktop.
use std::sync::RwLock;
fn main() {
let connection = Connection::new();
// Depends on `Send` to move the connection "onto" the thread.
let thread = std::thread::spawn(move || {
connection.write();
println!("{}", connection.read());
// The connection is dropped here.
});
thread.join().unwrap();
let connection: &'static Connection = Box::leak(Box::new(Connection::new()));
// Depends on `Sync` to share a reference with multiple threads.
let threads = (0..10).map(|_| {
std::thread::spawn(move || {
connection.write();
})
});
threads.for_each(|thread| thread.join().unwrap());
println!("{}", connection.read());
}
struct Connection {
lock: RwLock<usize>,
_handle: *const std::ffi::c_void,
}
unsafe impl Send for Connection {}
unsafe impl Sync for Connection {}
impl Connection {
fn new() -> Self {
Connection {
lock: RwLock::new(0),
_handle: std::ptr::null(),
}
}
fn write(&self) {
let mut writer = self.lock.write().unwrap();
*writer += 1;
}
fn read(&self) -> usize {
let reader = self.lock.read().unwrap();
*reader
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment