1

I had a code similar to this:

use std::thread;

fn main() {
    let mut prefe: Prefe = Prefe::new();
    start(&prefe).join();
    println!("Test {}", prefe.cantidad);
}

fn start(pre: &Prefe) -> thread::JoinHandle<i32> {
    thread::spawn(move || {
        std::thread::sleep(std::time::Duration::from_secs(50));
        let t: i32 = 3 as i32;
        t
    })
}

But when trying to use this:

std::thread::sleep(std::time::Duration::from_secs(pre.minutos_pom_corto));

I get this error:

error[E0477]: the type `[closure@src/main.rs:15:19: 22:6 pre:&Prefe]` does not fulfill the required lifetime
  --> src/main.rs:15:5
   |
15 |     thread::spawn(move || {
   |     ^^^^^^^^^^^^^
   |
   = note: type must outlive the static lifetime

After reading some things and Arc, I have this code which seems to work:

use std::thread;
use std::sync::Arc;

fn main() {
    let mut prefe: Prefe = Prefe::new();
    let test = Arc::new(prefe);
    start(test).join();    
    //println!("Test {}", prefe.cantidad); // <- With this commented
}

fn start(pre: Arc<Prefe>) -> thread::JoinHandle<i32> {
    thread::spawn(move || {
        std::thread::sleep(std::time::Duration::from_secs(pre.minutos_pom_corto));
        let t: i32 = 3 as i32;
        t
    })
}

Without commenting println!("Test {}", prefe.cantidad);, I get this error:

 let test = Arc::new(prefe);
    |                ----- value moved here

I tried the following:

//..
let test = Arc::new(&prefe);
//..

fn start(pre: Arc<&Prefe>) -> thread::JoinHandle<i32> {

But I get an error similar to the first one

error[E0477]: the type `[closure@src/main.rs:19:19: 26:6 pre:std::sync::Arc<&Prefe>]` does not fulfill the required lifetime
  --> src/main.rs:19:5
   |
19 |     thread::spawn(move || {
   |     ^^^^^^^^^^^^^
   |
   = note: type must outlive the static lifetime

I tried the following changes but it still does not work:

    //..
    let test = Arc::new(&prefe);
    start(&test).join();
    println!("{}", prefe.cantidad);
    //..

fn start(pre: &Arc<&Prefe>) -> thread::JoinHandle<i32> {
    //..
    let test = Arc::new(&prefe);
    let f = test.clone();
    start(&f).join();

    println!("{}", prefe.cantidad);
    //..

fn start(pre: &Arc<&Prefe>) -> thread::JoinHandle<i32> {

How can I fix this error, or what is the correct way to do what is shown?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Angel Angel
  • 19,670
  • 29
  • 79
  • 105
  • 1
    TL;DR: There's no guarantee that your reference to `Prefe` will live longer than the thread does. You need to transfer ownership to the thread instead. You can use `Arc` to have shared ownership, but you need to explicitly `.clone()` it before giving it away if you need to keep ownership. – Shepmaster May 08 '17 at 22:22
  • 1
    Really your comment, it was the one that helped me do this `let test = Arc::new(prefe); let f = test.clone(); start(f).join(); println!("{}", test.cantidad);` thanks again. – Angel Angel May 08 '17 at 22:36

0 Answers0