I'm trying to write a simple tcp server which would read and broadcast messages.
I'm using Tokio, but I think it's more of a general Rust question.
I have an Arc with a shared state:
let state = Arc::new(Mutex::new(Shared::new(server_tx)));
Later I want to spawn 2 threads which would use a reference to that state:
let server = listener.incoming().for_each(move |socket| {
// error[E0382]: capture of moved value: `state`
process(socket, state.clone());
Ok(())
}).map_err(|err| {
println!("accept error = {:?}", err);
});
let receive_sensor_messages = sensors_rx.for_each(move |line| {
println!("Received sensor message, broadcasting: {:?}", line);
// error[E0597]: borrowed value does not live long enough
// error[E0507]: cannot move out of borrowed content
for (_, tx) in state.clone().lock().unwrap().clients {
tx.unbounded_send(line.clone()).unwrap();
}
Ok(())
}).map_err(|err| {
println!("line reading error = {:?}", err);
});
As far as I understand what it's trying to tell me is that state is borrowed in the first closure listener.incoming().for_each(move |socket| { so when I try to do it again in sensors_rx.for_each(move |line| { it's saying it's not possible.
My question is how do I solve it? Isn't Arc supposed to solve the issue of sharing a variable between threads?
I tried different combinations of clone (doing clone outside of the closure and then doing clone inside again), but none worked.
Cheers!