Created
March 21, 2020 20:46
-
-
Save cameronp98/4a078d12138a014c660570944973f2cb to your computer and use it in GitHub Desktop.
Change a function from another task
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
| 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