Hello,
I'm very new at Rust, and I am exploring threads at the moment
I'm trying to get the main start a thread: the main thread accepts the user's inputs and the second thread (task::spawn
) sends the user's input to the connection (streams).
pub fn main() {
let (broker_sender, broker_receiver) = mpsc::unbounded::<Event>();
task::spawn(accept_loop("127.0.0.1:7777", broker_receiver));
loop {
let mut user_input = String::new();
io::stdout().flush().unwrap();
io::stdin().read_line(&mut user_input).unwrap();
let user_input_clean = user_input.trim();
if user_input_clean.starts_with("/send") {
let to_send: String = user_input_clean.chars().skip(5).collect();
broker_sender.send(Event::Message { msg: to_send });
}
}
}
async fn accept_loop(
addr: impl ToSocketAddrs,
broker: Receiver<Event>,
) -> Result<(), std::io::Error> {
let listener = TcpListener::bind(addr).await?;
let mut incoming = listener.incoming();
let broker = Arc::new(broker);
while let Some(stream) = incoming.next().await {
let stream = stream?;
println!("Accepting from: {}", stream.peer_addr()?);
let stream = Arc::new(stream);
task::spawn(connection_loop(Arc::clone(&stream), broker));
}
Ok(())
}
async fn connection_loop(
stream: Arc<TcpStream>,
broker: Arc<Receiver<Event>>,
) -> Result<(), std::io::Error> {
let mut stream = &*stream;
//let broker_value = Arc::clone(&broker);
while let Ok(event) = broker.try_next() {
match event.unwrap() {
Event::Message { msg } => {
stream.write_all(msg.as_bytes());
}
Event::NewPeer { ip_port, stream } => {}
}
}
Ok(())
}
My current issue is with the mpsc::unbounded
. I figure out that I need the broker to communicate between the thread, but I keep getting compilation errors. I think I need to use Arc,
but I have had mild success. Currently, the code above error is cannot borrow data in an
Arc as mutable
. Trying to use the commented line, change the error for cannot borrow data in an
Arc as mutable
. I also have tried to do like the stream and use &*
to access the broker receiver, but it gives cannot borrow
*brokeras mutable, as it is behind a
& reference
.
Let me know if I am using the wrong technic to share data from one thread to another one or to guide me to the right path. Thanks in advance!