Mpsc sender.receiver

pub struct Channel<'a> {
    pub task_sender: Arc<Mutex<mpsc::Sender<&'a TaskAction>>>,
    pub task_receiver: Arc<Mutex<mpsc::Receiver<&'a TaskAction>>>
}

impl <'a> Channel<'a> {
    pub fn new() -> Channel<'a> {
        let (sender, receiver) = mpsc::channel();
        Channel {
            task_sender: Arc::new(Mutex::new(sender)),
            task_receiver: Arc::new(Mutex::new(receiver))
        }
    }

    pub fn listen<F, E>(&mut self, handler: F, err: E)
    where 
        F : Fn(&TaskAction) + Sync + Send + 'a,
        E : Fn() + Sync + Send + 'a
    {
        let cloned = self.task_receiver.clone();

        thread::spawn(move || {
            loop {

impl <'a> Channel<'a> {
   |       -- lifetime `'a` defined here
...
23 |     pub fn listen<F, E>(&mut self, handler: F, err: E)
   |                         --------- `self` is a reference that is only valid in the method body
...
28 |         let cloned = self.task_receiver.clone();
   |                      ^^^^^^^^^^^^^^^^^^^^^^^^^^
   |                      |
   |                      `self` escapes the method body here
   |                      argument requires that `'a` must outlive `'static`

error happened becuase self will just escape and the way i wrote task_receiver.clone() is also unreasonable

im thinking about create a listen method, basically i want it like there is always a second thread that listen to certain action and react, but the way i code is defintely wrong the structure thing( new Channel{} )

any advice or ideas would be much appreciated!

Don't use lifetimes. As a rule of thumb, everytime the compiler complains that something must outlive 'static it is telling you that you should be using owned types instead.

1 Like

yes you are right

You can't send a reference over a channel because the value referenced must stay alive/active until the message is processed. So instead of '&TaskAction you would send TaskAction. Did you try that?

2 Likes

yes bro send TaskAction worked really appreciate your help

1 Like

Also, why do you have an Arc<Mutex<mpsc::Sender<_>>>? You can just clone the sender itself. (mpsc means multiple producer single consumer). You could also look into using an mpmc channel.

hi bro,

when i use mpmc it errored, error[E0658]: use of unstable library feature 'mpmc_channel'

so i use mpsc but wrap a arc mutex

at my listen funciton there is a thread::spawn so i need to clone the receiver, everything works fine just that the channel always closed(becuase of sender dropped and im still working on this problem)

std::sync::mpmc is indeed not yet stable, but there are crates with mpmc channels (most notably crossbeam). But of course, you can still use mpsc, I just thought it was worth a mention.

1 Like

i will check crossbeam later thanks