I'm trying to adapt code from this gist to make something like a pool of workers that could update data simultaneously for me, so I could get it from them via mpsc::channel
.
I want to build this pool of workers using a Vec<String>
as input, telling it how many workers will be created. I guess the input must be a Vec<String>
because it is dynamically built before the pool is created.
This is a basic snippet for result replication:
use std::{
collections::HashMap,
sync::{
mpsc::{self, Receiver, Sender},
Arc, Mutex, RwLock,
},
thread,
};
#[derive(Debug)]
pub struct Pool {
workers: RwLock<HashMap<String, Arc<Mutex<Worker>>>>,
}
impl Pool {
pub fn new(symbols: Vec<String>) -> Pool {
let mut workers: HashMap<String, Arc<Mutex<Worker>>> = HashMap::new();
for (s, w) in symbols.iter().map(|symbol| {
(
symbol,
Arc::new(Mutex::new({
let (in_tx, in_rx): (Sender<i32>, Receiver<i32>) = mpsc::channel();
let (out_tx, out_rx) = mpsc::channel();
let worker = Worker {
in_tx: in_tx,
out_rx: out_rx,
};
thread::spawn(move || {
println!("{}", symbol);
});
worker
})),
)
}) {
workers.insert(s.to_string(), w);
}
Pool {
workers: RwLock::new(workers),
}
}
}
#[derive(Debug)]
struct Worker {
pub in_tx: Sender<i32>,
pub out_rx: Receiver<i32>,
}
The compiler keeps complaining:
error[E0597]: `symbols` does not live long enough
--> src/lib.rs:18:23
|
18 | for (s, w) in symbols.iter().map(|symbol| {
| ^^^^^^^-------
| |
| borrowed value does not live long enough
| argument requires that `symbols` is borrowed for `'static`
...
40 | }
| - `symbols` dropped here while still borrowed
I think I kind of understand the reasons why it's happening, but I can't figure a way of working around this.