Skip to content

Instantly share code, notes, and snippets.

@barlog-m
Last active February 13, 2023 17:16
Show Gist options
  • Save barlog-m/567f0b322c248c89da8a728064438e56 to your computer and use it in GitHub Desktop.
Save barlog-m/567f0b322c248c89da8a728064438e56 to your computer and use it in GitHub Desktop.
/*
[dependencies]
futures = "0.3"
tokio = { version = "1", features = ["full"] }
rand = "0.8"
*/
use std::sync::Arc;
use rand::prelude::*;
type AppResult<T> = Result<T, Box<dyn std::error::Error + Send + Sync + 'static>>;
type DataRef = Arc<Vec<&'static str>>;
type StateRef = Arc<dyn State + Send + Sync>;
trait State {
fn data(&self) -> DataRef;
}
struct AppState {
data: DataRef
}
impl State for AppState {
fn data(&self) -> DataRef {
Arc::clone(&self.data)
}
}
async fn process(context: StateRef) -> AppResult<()> {
let n = thread_rng().gen_range(0..=2);
println!("{}", context.data()[n]);
Ok(())
}
#[tokio::main]
async fn main() {
let context = Arc::new(
AppState {
data: Arc::new(vec!["foo", "bar", "baz"]),
}) as StateRef;
let ha = tokio::spawn(process(Arc::clone(&context)));
let hb = tokio::spawn(process(Arc::clone(&context)));
let hc = tokio::spawn(process(Arc::clone(&context)));
let _ = futures::join!(ha, hb, hc);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment