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?