Skip to content

Instantly share code, notes, and snippets.

@sortofsleepy
Last active October 14, 2024 11:40
Show Gist options
  • Select an option

  • Save sortofsleepy/0e1052572941a0ca1e27acf8fc3885f1 to your computer and use it in GitHub Desktop.

Select an option

Save sortofsleepy/0e1052572941a0ca1e27acf8fc3885f1 to your computer and use it in GitHub Desktop.
setInterval-like behavior in Rust
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));
}
}
@sortofsleepy
Copy link
Copy Markdown
Author

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment