0

I am trying to pass the scheduler to a structure which will be used by a newly spawned thread. All of this needs to happen in a loop:

// Custom structure
struct CSlice<'a> {
      scheduler: &'a mut StandaloneScheduler
}

impl<'a> CSlice<'a> {
     fn start(self)
     {
          println!("Start slice");
          unsafe {
              control_nf(self.scheduler); // It gets passed on and on to different functions. 
          }
     }
}


fn main() {
    for i in 0..max_slices {
        let mut sched = StandaloneScheduler::new();
        let mut slice = CtrlSlice {
            scheduler: &mut sched}; // Error (Temp value/ Cannot borrow here)
        }
        thread::spawn(move || slice.start());
    }
}

What am I doing wrong? I tried cloning but Scheduler does not implement Clone. I know that the reference goes out of scope while passing it to the function but I'm not sure how to fix it.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
RNA
  • 11
  • First of, your code is not properly formatted. Please use `rustfmt` to do so. Second, your code does not compile, because you have missing braces `}`, e.g. for your `unsafe` block. Next your code is lacking a main function. Please create a [MCVE](https://stackoverflow.com/help/mcve) on the [Playground](https://play.rust-lang.org/) – hellow Jan 30 '19 at 15:35
  • 1
    Welcome to Stack Overflow! Please review how to create a [MCVE] and then [edit] your question to include it. We cannot tell what types, traits, fields, etc. are present in the code. Try to reproduce your error on the [Rust Playground](https://play.rust-lang.org) or in a brand new Cargo project. There are [Rust-specific MCVE tips](//stackoverflow.com/tags/rust/info) you can use to reduce your original code for posting here. – Shepmaster Jan 30 '19 at 15:48
  • 1
    Although the question does not have enough detail to say for sure, if I had to guess, I would say this is probably a duplicate of [How can I pass a reference to a stack variable to a thread?](https://stackoverflow.com/q/32750829/3650362) – trent Jan 30 '19 at 15:52
  • 1
    ... However, the first constraint you have to satisfy if you want to pass a reference to something to a thread, is that the something *actually* outlasts the thread, which is not the case here (`sched`'s lifetime is only for one iteration of the loop). Why don't you just have `CSlice` own the scheduler and not take it by reference at all? – trent Jan 30 '19 at 15:59

0 Answers0