Simple channel comunication

So I’m going through some tutorials and as always trying to make my own versions of the code to work (in order to better understand the things I am learning). This time I wanted to create a simple message-based communication over a channel. In the example below if I put everything into main () as demonstrated , everything works :slight_smile:

use std::sync::mpsc::channel;
use std::thread;
use std::time::Duration;
fn main() {
    let (send, recv) = channel();
    thread::spawn(move || {
        send.send("Hello there!".to_string()).unwrap();
        loop {
            thread::sleep(Duration::from_secs(3));
            send.send("Delayed for 3 seconds".to_string()).unwrap();
        }
    });

    loop {
        println!("{}", recv.recv().unwrap()); 
    }
}

But if I want to create an object from it (as in the example below), i get a different problem on every fix I make:

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

#[derive(Clone)]
struct Obj {
    send: Sender<String>,
    recv: Receiver<String>,
}

impl Obj {
    fn new() -> Self {
        let (send, recv) = channel();
        Obj {
            send: send,
            recv: recv,
        }
    }

    fn listen(self) {
        loop {
            println!("{}", self.recv.recv().unwrap());
        }
    }

    fn brodcast(self) {
        let x = self.send.clone();
        thread::spawn(move || {
            x.send("Hello there!".to_string()).unwrap();
            loop {
                thread::sleep(Duration::from_secs(3));
                x.send("Delayed for 3 seconds".to_string()).unwrap();
            }
        });
    }
}

fn main() {
    let obj = Obj::new();

    obj.brodcast();
   // do some stuff here
    obj.listen();
}

So finally I gave up and decided to post my problem here seeking your advice. Could someone please take a look at it and give pointers on what to do to make it work :slight_smile:

Thnx

You’d better paste your problems info detailed.

use std::sync::mpsc::{channel, Receiver, Sender};
use std::thread;
use std::time::Duration;
 
-#[derive(Clone)]
 struct Obj {
     send: Sender<String>,
     recv: Receiver<String>,
 }
-    fn brodcast(self) {
+    fn brodcast(&self) {
         let x = self.send.clone();
         thread::spawn(move || {
             x.send("Hello there!".to_string()).unwrap();
             loop {
                 thread::sleep(Duration::from_secs(3));
                 x.send("Delayed for 3 seconds".to_string()).unwrap();
             }
         });
     }

This works for me.

The basic issue is that Receiver is not clonable, so you cannot derive Clone for Obj. And because you cannot do that, you must avoid moving it when calling broadcast(), hence the borrow &self.

PS: Playground link. It’s always useful to provide one when you have a problem, it makes it much easier for people to play around with your problem! :ok_hand:

2 Likes