Last active
September 22, 2023 19:10
-
-
Save trvswgnr/613e6dece990518243bcc11fa3587004 to your computer and use it in GitHub Desktop.
fearless concurrency macro
This file contains hidden or 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
macro_rules! fearless { | |
($t:ty) => { | |
std::sync::Arc<std::sync::Mutex<$t>> | |
}; | |
($e:expr) => { | |
std::sync::Arc::new(std::sync::Mutex::new($e)) | |
}; | |
(clone $e:expr) => { | |
std::sync::Arc::clone(&$e) | |
}; | |
(lock $e:expr) => { | |
match $e.lock() { | |
Ok(guard) => guard, | |
Err(poisoned) => poisoned.into_inner(), | |
} | |
}; | |
(lock $e:expr, $err:expr) => {{ | |
match $e.lock() { | |
Ok(guard) => guard, | |
Err(_) => return $err, | |
} | |
}}; | |
} | |
fn main() { | |
#[derive(Debug)] | |
struct X(fearless!(String)); | |
let x = X(fearless!("h".to_string())); | |
println!("{:?}", x); | |
let data = fearless!(5); | |
let data_clone = fearless!(clone data); | |
let mut locked_data = fearless!(lock data_clone, println!("Mutex is poisoned")); | |
*locked_data += 1; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment