/
za
/
example_web_server_on_rust
Обзор
Документация
Войти
/
za
/
example_web_server_on_rust
Код
Запросы
0
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
src/lib.rs
63 строки
1 KB
Alexey Zabolotnov
first_commit
26 мар 2024, 15:19
26 мар 2024, 15:19
e900f2b
Код
Авторство
О чём код?
use std::{sync::mpsc, thread}; use std::sync::{Arc, Mutex}; struct Worker { id: usize, thread: thread::JoinHandle<()>, } pub struct ThreadPool { workers: Vec<Worker>, sender: mpsc::Sender<Job>, } //struct Job; type Job = Box<dyn FnOnce() + Send + 'static>; /// Create a new ThreadPool. /// /// The size is the number of threads in the pool. /// /// # Panics /// /// The `new` function will panic if the size is zero. impl ThreadPool { pub fn new(size: usize) -> ThreadPool { assert!(size > 0); let (sender, receiver) = mpsc::channel(); let receiver = Arc::new(Mutex::new(receiver)); let mut workers = Vec::with_capacity(size); for id in 0..size { workers.push(Worker::new(id, Arc::clone(&receiver))); } ThreadPool { workers, sender } } pub fn execute<F>(&self, f: F) where F: FnOnce() + Send + 'static, { let job = Box::new(f); self.sender.send(job).unwrap(); } } impl Worker { fn new(id: usize, receiver: Arc<Mutex<mpsc::Receiver<Job>>>) -> Worker { let thread = thread::spawn(move || { while let Ok(job) = receiver.lock().unwrap().recv() { println!("Worker {id} got a job; executing."); job(); } }); Worker { id, thread } } }