Communication between threads?

Hello, I already wanted to thank you all, because I really appreciate the community Rust :heart:

So I come from the javascript world and other events driven languages.
I usually do not have too much difficulty with the Rust language, but here I really feel like I'm doing something bad.
Is it really catastrophic? thanking you in advance :kissing_heart:

use std::sync::mpsc;
use std::thread;
use std::time::Duration;


fn main() {

    let (tx, rx) = mpsc::channel();

    let (tx2, rx2) = mpsc::channel();

    thread::spawn(move || {

        // Send a message
        tx.send("Bonjour Antoine :D").unwrap();

        // Waiting the acknowledgment of receipe
        loop {
            println!("Acknowledgment of receipe: {:?}", rx2.try_recv());
            thread::sleep(Duration::from_secs(1));
        }
    });

    // Display the received message
    println!("New message: {:?}", rx.recv());

    // Sending the acknowledgment of receipt
    tx2.send("Ok").unwrap();

    loop {}
}

Edit: It is just an example of implementation, to be able to easily show my problem

1 Like

I don't think so. What are you worried about?

1 Like

Inside the loop why are you using try_recv() instead of blocking with recv()? If you are just waiting to receive then that's exactly what recv() is for.

1 Like

I am worried because this implementation was present in the standard library (std::comm::duplex) but it was deleted.
So I deduced that it could have side effects that I did not know yet

I thought, to have the same result I had to use a mutex, but if everything is ok, i'm fine :slight_smile:

1 Like

Yup, in this exemple you're right :slight_smile:
But is only an "exemple" and in my "real problem" i've to do few computations when im waiting in the spawned thread

Do you use sleep in your real problem? Does your real problem involve an infinite loop? It will help us help you if you give a description of your real problem.

I am currently doing a gameboy advance emulator.
I needed a real debugger to better understand why some roms do not behave as expected.
So I decided to do a web debugger because I am very familiar with web technologies.
So I need a different thread to listen for websockets
But I need two-way comminications:

  • In a way, the debugger transmits commands to the emulator (next assembler instruction, add breakpoints, etc ...)
  • In another way, the emulator sends information to the websockets thread (memory dump, information on the cpu, etc ...)

It is a personal project, to learn rust and try to get good practices from the time of apprenticeship

I went looking for why it was removed, but I couldn't find it out. My vague memory is "these things were hard to actual compose with other things and it's easy enough to write yourself if you need it".

1 Like

Also you could use sync_channel with a size of 0.