How to mutate a global variable using tokio and futures

Hi,

Im new to rust and would like to know how to mutate a global variable using tokio/futures.

[dependencies]
tokio = { version = "0.3.0", features = ["rt", "rt-multi-thread", "macros", "time"] }

use tokio::time::{self, Duration};
use std::future::Future;
 
#[tokio::main]
async fn main() {

    let mut mutate = 0; // how do i increment this inside the interval ?

    set_interval(|| async {
        mutate = mutate + 1;
        println!("{}", mutate);
    }, 5000);
    
    time::sleep(Duration::from_millis(60000)).await;
}
 
 
fn set_interval<F, Fut>(mut task: F, dur: u64)
where
    F: Send + 'static + FnMut() -> Fut,
    Fut: Future<Output = ()> + Send + 'static,
{
    let mut interval = time::interval(Duration::from_millis(dur));
    tokio::spawn(async move {
        // Skip the first tick at 0ms.
        interval.tick().await;
        loop {
            interval.tick().await;
            tokio::spawn(task());
        }
    });
}

You will need to use an Arc to share it. Since it is an integer, you can use an Arc<AtomicU32>, but if the type is more complicated, you will need an Mutex.

I don't want to be annoying but I would really love to see an example. I've never used Arc before.

From the standard library documentation: Examples

Examples

Sharing some immutable data between threads:

use std::sync::Arc;
use std::thread;

let five = Arc::new(5);

for _ in 0..10 {
    let five = Arc::clone(&five);

    thread::spawn(move || {
        println!("{:?}", five);
    });
}

Sharing a mutable AtomicUsize:

use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::thread;

let val = Arc::new(AtomicUsize::new(5));

for _ in 0..10 {
    let val = Arc::clone(&val);

    thread::spawn(move || {
        let v = val.fetch_add(1, Ordering::SeqCst);
        println!("{:?}", v);
    });
}