threading

This commit is contained in:
0m.ax 2025-07-18 23:03:45 +02:00
parent 57880ef70a
commit c9d179c33f

View file

@ -5,6 +5,7 @@ use std::io::BufReader;
use std::net::{ToSocketAddrs, UdpSocket};
use std::time::Duration;
use std::sync::{Arc, Condvar, Mutex};
use std::thread;
// Constants from the C code
const QUEUE_LEN: usize = 1000;
@ -175,6 +176,34 @@ impl Display {
}
}
}
fn send_thread(&mut self) {
let consumer_pair = Arc::clone(&self.pair);
let consumer_handle = thread::spawn(move || {
let mut items_processed = 0;
loop {
let (lock, cvar) = &*consumer_pair;
let mut buffer = lock.lock().unwrap();
// Use a while loop to handle spurious wakeups.
// The thread will sleep until the buffer is no longer empty.
while buffer.is_empty() {
// `cvar.wait` atomically unlocks the mutex and waits.
// When woken, it re-locks the mutex before returning.
buffer = cvar.wait(buffer).unwrap();
}
// At this point, the buffer is not empty.
if let Some(item) = buffer.pop() {
println!(" Consumed: {}", item);
items_processed += 1;
}
drop(buffer);
thread::sleep(Duration::from_millis(300)); // Consumer is slow
}
});
}
}
fn main() {
@ -185,7 +214,7 @@ fn main() {
let mut display = Display::new(DISPLAY_HOST, DISPLAY_PORT);
let mut frame_counter: u32 = 0;
// display.blank_screen();
display.send_thread();
loop {
for (i, bb) in images.iter_mut().enumerate() {