Block the emulator thread when idle

This commit is contained in:
Simon Gellis 2024-11-10 16:08:49 -05:00
parent e8b706df20
commit 99d6970323
1 changed files with 15 additions and 1 deletions

View File

@ -3,7 +3,7 @@ use std::{
path::{Path, PathBuf}, path::{Path, PathBuf},
sync::{ sync::{
atomic::{AtomicBool, Ordering}, atomic::{AtomicBool, Ordering},
mpsc::{self, TryRecvError}, mpsc::{self, RecvError, TryRecvError},
Arc, Arc,
}, },
}; };
@ -94,19 +94,33 @@ impl Emulator {
let mut eye_contents = vec![0u8; 384 * 224 * 2]; let mut eye_contents = vec![0u8; 384 * 224 * 2];
let mut audio_samples = vec![]; let mut audio_samples = vec![];
loop { loop {
let mut idle = true;
if self.running.load(Ordering::Acquire) { if self.running.load(Ordering::Acquire) {
idle = false;
self.sim.emulate_frame(); self.sim.emulate_frame();
} }
if let Some(renderer) = &mut self.renderer { if let Some(renderer) = &mut self.renderer {
if self.sim.read_pixels(&mut eye_contents) { if self.sim.read_pixels(&mut eye_contents) {
idle = false;
renderer.render(&eye_contents); renderer.render(&eye_contents);
} }
} }
self.sim.read_samples(&mut audio_samples); self.sim.read_samples(&mut audio_samples);
if !audio_samples.is_empty() { if !audio_samples.is_empty() {
idle = false;
self.audio.update(&audio_samples); self.audio.update(&audio_samples);
audio_samples.clear(); audio_samples.clear();
} }
if idle {
// The game is paused, and we have output all the video/audio we have.
// Block the thread until a new command comes in.
match self.commands.recv() {
Ok(command) => self.handle_command(command),
Err(RecvError) => {
return;
}
}
}
loop { loop {
match self.commands.try_recv() { match self.commands.try_recv() {
Ok(command) => self.handle_command(command), Ok(command) => self.handle_command(command),