Created
May 7, 2022 02:39
-
-
Save ctulek/3cab995e0de0b8938191d5db8e75be3a to your computer and use it in GitHub Desktop.
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
extern crate core; | |
extern crate minifb; | |
use std::{mem, thread}; | |
use std::ops::Deref; | |
use std::sync::Arc; | |
use std::sync::atomic::{AtomicI8, AtomicU32, Ordering}; | |
use std::thread::JoinHandle; | |
use std::time::Duration; | |
use minifb::{Key, Window, WindowOptions}; | |
use rand::prelude::*; | |
const WIDTH: usize = 800; | |
const HEIGHT: usize = 800; | |
fn main() { | |
let mut buffer: Vec<AtomicU32> = Vec::with_capacity(WIDTH * HEIGHT); | |
for _ in 0..WIDTH * HEIGHT { | |
buffer.push(AtomicU32::new(0)); | |
} | |
let buffer: Arc<[AtomicU32]> = Arc::from(buffer); | |
let mut window = Window::new( | |
"Test - ESC to exit", | |
WIDTH, | |
HEIGHT, | |
WindowOptions::default(), | |
) | |
.unwrap_or_else(|e| { | |
panic!("{}", e); | |
}); | |
// Limit to max ~60 fps update rate | |
window.limit_update_rate(Some(std::time::Duration::from_micros(16600))); | |
let mut threads: Vec<JoinHandle<_>> = Vec::new(); | |
let step = WIDTH * HEIGHT / 2; | |
let running_threads = Arc::new(AtomicI8::new(0)); | |
for position in (0..WIDTH * HEIGHT).step_by(step) { | |
println!("Position: {}", position); | |
let buffer = buffer.clone(); | |
let running_threads = running_threads.clone(); | |
let join_handle = thread::spawn(move || { | |
println!("Position: {} Thread", position); | |
running_threads.fetch_add(1, Ordering::SeqCst); | |
let mut counter = 0usize; | |
for i in position..(position + step) { | |
buffer[i].store(random(), Ordering::Relaxed); | |
counter += 1; | |
if counter % 10000 == 0 { | |
thread::sleep(Duration::from_secs(1)); | |
} | |
} | |
running_threads.fetch_sub(1, Ordering::SeqCst); | |
}); | |
threads.push(join_handle); | |
} | |
thread::sleep(Duration::from_secs(1)); | |
println!("Running threads: {}", running_threads.load(Ordering::Acquire)); | |
while window.is_open() && !window.is_key_down(Key::Escape) { | |
unsafe { | |
let window_buffer: &[u32] = mem::transmute(buffer.deref()); | |
window | |
.update_with_buffer(window_buffer, WIDTH, HEIGHT) | |
.unwrap(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment