Hello Rustaceans,
I'm trying to make subsequent threads to use clones of the same tx
to send messages to the first thread. So I wrapped tx
in an Arc
. My understanding is that this should move tx
to the heap, and there it should live until all references to it are gone.
But the compiler complains that tx doesn't live long enough. Isn't that the exact problem that the Arc
is supposed to solve? Code below, and thanks in advance for any insights.
use std::sync::Arc;
use std::sync::Mutex;
use std::thread;
pub fn t1(rx1: Receiver<String>, tx2: Arc<Mutex<Sender<String>>>) {
println!("1");
}
pub fn t2(rx2: Receiver<String>, tx1: Arc<Mutex<Sender<String>>>) {
println!("2");
}
pub fn main() {
let (tx1, rx1) = std::sync::mpsc::channel();
let tx1 = Arc::new(Mutex::new(tx1));
let (tx2, rx2) = std::sync::mpsc::channel();
let tx2 = Arc::new(Mutex::new(tx2));
let j1 = thread::spawn( || {
t1(rx1, tx2.clone());
});
let j2 = thread::spawn( || {
let f = t2(rx2, tx1.clone());
});
j1.join();
j2.join();
}```