atranscoder-rpc/src/thread_pool.rs

82 lines
2.3 KiB
Rust
Raw Normal View History

use ffmpeg_next::log::Level;
2024-05-25 19:22:08 +03:00
use std::sync::mpsc::{self, Receiver, Sender};
2024-05-25 21:29:53 +03:00
use std::sync::{Arc, Mutex};
2024-05-25 19:22:08 +03:00
use std::thread;
use std::time::Duration;
2024-05-25 21:29:53 +03:00
use tracing::{debug, error};
2024-05-25 19:22:08 +03:00
use crate::task::Task;
pub struct ThreadPool {
workers: Vec<Worker>,
sender: Sender<Task>,
}
impl ThreadPool {
pub(crate) fn new(num_threads: Option<usize>) -> Self {
let num_threads = num_threads.unwrap_or_else(num_cpus::get);
let (sender, receiver) = mpsc::channel();
let receiver = Arc::new(Mutex::new(receiver));
let workers = (0..num_threads)
.map(|id| Worker::new(id, Arc::clone(&receiver)))
.collect();
ThreadPool { workers, sender }
}
pub fn enqueue(&self, task: Task) {
if let Err(e) = self.sender.send(task) {
error!("failed to send task to the queue: {:?}", e);
}
}
}
struct Worker {
id: usize,
thread: Option<thread::JoinHandle<()>>,
}
impl Worker {
fn new(id: usize, receiver: Arc<Mutex<Receiver<Task>>>) -> Self {
2024-05-25 20:32:54 +03:00
let thread = thread::spawn(move || {
ffmpeg_next::init()
.unwrap_or_else(|err| tracing::error!("couldn't init FFmpeg: {:?}", err));
ffmpeg_next::util::log::set_level(
if std::env::var("FFMPEG_VERBOSE").unwrap_or_default() == "1" {
Level::Trace
} else {
Level::Quiet
},
);
2024-05-25 19:22:08 +03:00
2024-05-25 20:32:54 +03:00
loop {
let task = {
let lock = receiver.lock().unwrap();
lock.recv()
};
match task {
Ok(task) => {
debug!("worker {} got a task; executing.", id);
2024-05-26 12:32:09 +03:00
if let Err(err) = task.execute() {
error!("worker {} failed to finish the task: {:?}", id, err);
}
2024-05-25 20:32:54 +03:00
}
Err(e) => {
error!("worker {} failed to receive task: {:?}", id, e);
thread::sleep(Duration::from_secs(1)); // sleep to avoid busy-looping
}
2024-05-25 19:22:08 +03:00
}
}
});
Worker {
id,
thread: Some(thread),
}
}
}