I'm running into an issue with efficiently and correctly waiting for a certain value before doing something.
So I've got a websocket server that waits for input in one thread and I have this thread below that I want to constantly be checking the gamestate. However, when I kick it off it immediately runs at 100% CPU - I know it's because it's constantly looping and checking the game_state struct. I'm curious is there a way to make this more async? Or at least make it wait for a specific value, in this instance a value greater than 1. I think there should be a way to do this but if someone could point me in the right direction that'd be awesome.
async fn main_loop(mut game: Arc<Mutex<Game>>) {
let mut first_started = true;
loop {
let mut game_state = game.lock().unwrap();
if game_state.world.get_players().lock().unwrap().len() > 1 {
if first_started {
println!("SHOWTIME!");
game_state.new_round();
game_state.ready_users();
game_state.start_round();
}
//.....
//other game state checks.....
}
}
}
Possibly. maybe, you could use a channel to communicate between that thread that is waiting for players and whatever other thread is accepting players.
With MPSC channels you could .send() a message every time the number of players in the world changes which would be '.recv()' by your loop above.
No more need for that Arc<Mutex>, pass the channel instead.
oh, that's totally the way to do this. I can have that thread just be updated by people connecting/disconnecting in the other. That's really helpful, it's funny I'm already using channels elsewhere just didn't think to use them this way. I'd still need the Arc<Mutex<>> if I wanted to call methods on that struct though right? I'd need to pass it to the thread just wouldn't need to constantly lock it.