Skip to content

Instantly share code, notes, and snippets.

@meshula
Created March 15, 2023 02:02
Show Gist options
  • Save meshula/336b2dbd1560898329c45733e7a90fee to your computer and use it in GitHub Desktop.
Save meshula/336b2dbd1560898329c45733e7a90fee to your computer and use it in GitHub Desktop.
test-nanoexrinfo.rs
use std::env;
use std::path::PathBuf;
use crossbeam_channel::{Receiver, Sender};
use std::sync::{Arc, Mutex};
use std::thread;
pub struct ThreadPool {
sender: Sender<Box<dyn FnOnce() + Send + 'static>>,
}
impl ThreadPool {
pub fn new(num_threads: usize) -> ThreadPool {
let (sender, receiver) = crossbeam_channel::unbounded();
let receiver = Arc::new(Mutex::new(receiver));
for _ in 0..num_threads {
let receiver = receiver.clone();
let sender = sender.clone();
thread::spawn(move || loop {
let message = receiver.lock().unwrap().recv().unwrap();
message();
sender.send(message).unwrap();
});
}
ThreadPool { sender }
}
pub fn execute<F>(&self, f: F)
where
F: FnOnce() + Send + 'static,
{
self.sender.send(Box::new(f)).unwrap();
}
}
use std::fs;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::thread;
use std::thread::JoinHandle;
fn recurse_directory(directory_path: &Path, thread_pool: &ThreadPool) {
for entry in fs::read_dir(directory_path).unwrap() {
let entry = entry.unwrap();
let path = entry.path();
if path.is_dir() {
// Recursively process the subdirectory in a new task
let thread_pool = thread_pool.clone();
thread_pool.execute(move || {
recurse_directory(&path, &thread_pool);
});
} else if path.is_file() && path.extension() == Some("exr".as_ref()) {
// Print the file name in a new task
let path = path.to_path_buf();
thread_pool.execute(move || {
print_file_name(&path);
});
}
}
}
fn main() {
// Get the command line argument for the directory to recurse
let args: Vec<String> = env::args().collect();
if args.len() != 2 {
println!("Usage: {} <directory>", args[0]);
return;
}
let directory_path = PathBuf::from(&args[1]);
// Create a thread pool with 4 threads
let thread_pool = ThreadPool::new(4);
// Recurse the directory in a new task
thread_pool.submit(move || {
recurse_directory(directory_path, &thread_pool);
});
// Wait for all tasks to complete
thread_pool.join();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment