I have a Question about using channels among multiple threads in Rust. I am working on a Networking project and this is and example I have:
fn main() {
let mut thisMesh = Mesh::new();
let (tx, rx): (Sender<(&Message, &Station)>, Receiver<(&Message, &Station)>) = mpsc::channel();
}
fn analyzer(mesh: &mut Mesh, sender_channel: mpsc::Sender<(&Message, &Station)>, message: &Message) {
if !mesh.self_station.sent_stations.contains_key(message.id.as_str()) {
mesh.self_station.sent_stations.insert(message.id.to_string(), HashSet::new());
}
scan_for_stations(mesh);
for station in mesh.station_list.iter() {
if mesh.self_station.message_sent_to_given_station(message, station) {
continue;
}
sender_channel.send((message, station));
}
}
I get these errors:
error[E0623]: lifetime mismatch
--> src/main.rs:93:39
|
84 | fn sender_analyzer(mesh: &mut Mesh, sender_channel: mpsc::Sender<(&Message, &Station)>, message: &Message) {
| --------- --------
| |
| these two types are declared with different lifetimes...
...
93 | sender_channel.send((message, station));
| ^^^^^^^ ...but data from mesh
flows into sender_channel
here
error[E0623]: lifetime mismatch
--> src/main.rs:93:30
|
84 | fn sender_analyzer(mesh: &mut Mesh, sender_channel: mpsc::Sender<(&Message, &Station)>, message: &Message) {
| -------- -------- these two types are declared with different lifetimes...
...
93 | sender_channel.send((message, station));
^^^^^^^ ...but data from message flows into sender_channel here |
---|
I solved it using life time, but I am not sure If this is a correct way of doing it in rust: |
here is the change that compiles: |
fn analyzer<'a>(mesh: &'a mut Mesh, sender_channel: mpsc::Sender<(&'a Message, &'a Station)>, message: &'a Message) {
if !mesh.self_station.sent_stations.contains_key(message.id.as_str()) {
mesh.self_station.sent_stations.insert(message.id.to_string(), HashSet::new());
}
scan_for_stations(mesh);
for station in mesh.station_list.iter() {
if mesh.self_station.message_sent_to_given_station(message, station) {
continue;
}
sender_channel.send((message, station));
}
}
Is this is the right way to do it in rust?
in other programming languages I defined Mesh and Channel as static variable so I can use it during the life time of whole program like this:
private static Mesh Mesh { get; set; } = new Mesh();
private static ConcurrentQueue SenderCommunicationChannel { get; } = new ConcurrentQueue();
but I am passing it in rust. So is this the right way in Rust? Would you please Assist?