Hello everyone, I'm new in Rust and trying to implement thread pool method described in book "The Rust programming language" for my tasks.
bin:
use pthreadpool::ThreadPool;
const THREADS_MAX: usize = 2;
fn test_func(s: String) {
println!("{}", s.to_uppercase());
}
fn thread_manager<T>(data: Vec<T>, f: fn(t: T)) {
let pool = ThreadPool::new(THREADS_MAX);
for d in data {
pool.execute(|| {
test_func(d);
})
}
}
fn main() {
let strings = vec![
"hello".to_string(),
"world".to_string(),
"testing".to_string(),
"good enough".to_string(),
];
thread_manager(strings, test_func);
}
lib:
use std::sync::{Arc, Mutex, mpsc};
use std::thread;
// contains:
// 1. vector of Workers
// 2. transmitting side of pipe
#[allow(dead_code)]
pub struct ThreadPool {
workers: Vec<Worker>,
sender: mpsc::Sender<Job>,
}
// contains:
// 1. id of Worker
// 2. thread
#[allow(dead_code)]
struct Worker {
id: usize,
thread: thread::JoinHandle<()>,
}
type Job = Box<dyn FnOnce() + Send + 'static>;
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 || loop {
let job = receiver.lock().unwrap().recv().unwrap();
println!("Worker {} got a job; executing.", id);
job();
});
Worker { id, thread }
}
}
I did a thread_manager function that accept as arguments some Vec and some function. So, in main() i pass vector of strings and test_func() that fit the description to f: fn(t: T).
But i got an error that i dont know to to fix:
--> src/bin/main.rs:44:23
|
39 | fn thread_manager<T>(data: Vec<T>, f: fn(t: T)) {
| - this type parameter
...
44 | test_func(d);
| ^ expected struct `String`, found type parameter `T`
|
= note: expected struct `String`
found type parameter `T`