Skip to content

Instantly share code, notes, and snippets.

@su8
Created November 12, 2025 17:58
Show Gist options
  • Select an option

  • Save su8/0de78632455c0a6d9488452a1eaad780 to your computer and use it in GitHub Desktop.

Select an option

Save su8/0de78632455c0a6d9488452a1eaad780 to your computer and use it in GitHub Desktop.
main14.rs
use std::path::Path;
use std::process::Command;
use std::fs::File;
use std::io::Write;
use std::thread;
use std::sync::mpsc;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
fn optimize_pdf(pdf_path: &Path) {
let output_path = pdf_path.with_name(format!("optimized_{}", pdf_path.file_name().unwrap().to_str().unwrap()));
let mut cmd = Command::new("gs");
cmd.arg("-sDEVICE=pdfwrite");
cmd.arg("-dNOPAUSE");
cmd.arg("-dBATCH");
cmd.arg("-dQUIET");
cmd.arg(&format!("-sOutputFile={}", output_path.display()));
cmd.arg(pdf_path.display());
let _ = cmd.spawn().unwrap().wait().unwrap();
}
fn main() {
let pdf_files = Path::new(".").read_dir().unwrap().filter_map(|e| e.ok().and_then(|e| e.file_name().ok()).map(|n| n.to_str().unwrap().to_string()).filter(|n| n.ends_with(".pdf")).collect::<Vec<_>>();
let (tx, rx) = mpsc::channel();
let (done, done_tx) = mpsc::channel();
let pdf_files_len = Arc::new(AtomicUsize::new(pdf_files.len()));
for pdf_file in pdf_files {
let tx = tx.clone();
let done_tx = done_tx.clone();
let pdf_files_len = Arc::clone(&pdf_files_len);
thread::spawn(move || {
optimize_pdf(&Path::new(&pdf_file));
tx.send(()).unwrap();
pdf_files_len.fetch_sub(1, Ordering::SeqCst);
if pdf_files_len.load(Ordering::SeqCst) == 0 {
done_tx.send(()).unwrap();
}
});
}
for _ in 0..8 {
rx.recv().unwrap();
}
done.recv().unwrap();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment