Skip to content

Instantly share code, notes, and snippets.

@cameronp98
Created March 21, 2020 20:46
Show Gist options
  • Save cameronp98/4a078d12138a014c660570944973f2cb to your computer and use it in GitHub Desktop.
Save cameronp98/4a078d12138a014c660570944973f2cb to your computer and use it in GitHub Desktop.
Change a function from another task
use tokio::time::{self, Duration};
use tokio::sync::Mutex;
use std::sync::Arc;
type FooFn = dyn Fn(u32) -> u32 + Send;
#[tokio::main]
async fn main() {
let foo: Arc<Mutex<Option<Box<FooFn>>>> = Arc::new(Mutex::new(None));
{
let foo = foo.clone();
tokio::spawn(async move {
let mut interval = time::interval(Duration::from_secs(2));
for i in 0u32.. {
interval.tick().await;
let mut foo = foo.lock().await;
println!("changing foo");
*foo = Some(Box::new(move |n| n * i));
}
});
}
let mut interval = time::interval(Duration::from_secs(1));
for i in 0u32.. {
interval.tick().await;
println!("Calling foo");
if let Some(ref foo) = *foo.lock().await {
println!("foo({}) = {}", i, foo(i));
} else {
println!("no foo");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment