0

Im reading this example on thread communication:

use std::sync::mpsc::{Sender, Receiver};
use std::sync::mpsc;
use std::thread;

static NTHREADS: i32 = 3;

fn main() {
    // Channels have two endpoints: the `Sender<T>` and the `Receiver<T>`,
    // where `T` is the type of the message to be transferred
    // (type annotation is superfluous)
    let (tx, rx): (Sender<i32>, Receiver<i32>) = mpsc::channel();
    let mut children = Vec::new();

    for id in 0..NTHREADS {
        // The sender endpoint can be copied
        let thread_tx = tx.clone();

        // Each thread will send its id via the channel
        let child = thread::spawn(move || {
            // The thread takes ownership over `thread_tx`
            // Each thread queues a message in the channel
            thread_tx.send(id).unwrap();

            // Sending is a non-blocking operation, the thread will continue
            // immediately after sending its message
            println!("thread {} finished", id);
        });

        children.push(child);
    }

    // Here, all the messages are collected
    let mut ids = Vec::with_capacity(NTHREADS as usize);
    for _ in 0..NTHREADS {
        // The `recv` method picks a message from the channel
        // `recv` will block the current thread if there are no messages available
        ids.push(rx.recv());
    }

    // Wait for the threads to complete any remaining work
    for child in children {
        child.join().expect("oops! the child thread panicked");
    }

    // Show the order in which the messages were sent
    println!("{:?}", ids);
}

I'm having a problem with these 2 lines:

thread_tx.send(id).unwrap();
println!("thread {} finished", id);

How does send work? It sends a copy? That's the only way I can still use id after using it in send, isn't it?

If I'm correct, then how to send in non copy mode? I can send in an 'own way', that is, the send function now owns it, but I couldn't use it again. I can also send in a borrow way, as a reference, but I couldn't use it again unless the other thread releases it.

Guerlando OCs
  • 1,886
  • 9
  • 61
  • 150

1 Answers1

3

How does send work? It sends a copy? That's the only way I can still use id after using it in send, isn't it?

Send sends whatever you give it. Here it sends a copy because id is an i32 which is Copy, but it doesn't intrinsically care,

The documentation of the Copy trait has some explanations. There's also this old answer which provides a shorter (but less extensive) explanation.

Masklinn
  • 34,759
  • 3
  • 38
  • 57