Reputation: 37
Let's say I have two threads that have different intent (T1, T2). T1 is responsible for pushing messages into a queue and T2 is responsible for popping messages. How do I implement a way to run T1 and T2 together?
I tried looking at existing multithreaded implementations and examples in rust but most of them are about spawning multiple threads for the same job.
//using an Arc object of an ArrayQueue
let handle1 = thread::spawn( move || {
//clone arc object
//push
});
let handle2 = thread::spawn( move || {
//clone arc object
//pop
});```
Upvotes: 2
Views: 1773
Reputation: 15663
Why do you think the threads are not running concurrently ? For easily passing data between threads you can use the MPSC channel from the std library:
use std::time::Duration;
fn main() {
let (sender, receiver) = std::sync::mpsc::channel();
let sending_thread = std::thread::spawn(move || {
for i in 0..10 {
println!("[{:?}] Sending: {}", std::thread::current().id(), i);
sender.send(i).unwrap();
std::thread::sleep(Duration::from_secs(1));
}
});
let receiving_thread = std::thread::spawn(move || {
for i in receiver {
println!("[{:?}] Received: {}", std::thread::current().id(), i);
}
});
let _ = sending_thread.join();
let _ = receiving_thread.join();
println!("Done");
}
Upvotes: 2