Last active
October 14, 2024 11:40
-
-
Save sortofsleepy/0e1052572941a0ca1e27acf8fc3885f1 to your computer and use it in GitHub Desktop.
setInterval-like behavior in Rust
This file contains 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 std::sync::{Arc, Mutex}; | |
use std::thread; | |
use std::time::Duration; | |
#[derive(Clone)] | |
struct Cube { | |
i: Arc<Mutex<i32>>, | |
} | |
impl Cube { | |
pub fn new() -> Cube { | |
Cube { i: Arc::new(Mutex::new(0)) } | |
} | |
pub fn append(&mut self) { | |
let mut val = self.i.lock().unwrap(); | |
*val+=1; | |
} | |
pub fn get_value(&self) -> i32 { | |
let mut val = self.i.lock().unwrap(); | |
*val | |
} | |
pub fn start(&mut self) { | |
let mut me = self.clone(); | |
thread::spawn(move || { | |
loop { | |
let wait = Duration::from_millis(500); | |
me.append(); | |
thread::sleep(wait); | |
} | |
}); | |
} | |
} | |
fn main() { | |
let mut cube = Cube::new(); | |
cube.start(); | |
loop{ | |
println!("{}",cube.get_value()); | |
thread::sleep(Duration::from_millis(500)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Likely not the best method but simple enough for my use cases without having to use something like Tokio. Adapted after reading the thread here
https://users.rust-lang.org/t/using-thread-loop-inside-a-struct/66396/2