1

What's wrong with the following code?

fn main() {
    let a = 1;
    let handler = std::thread::spawn(||{
        dbg!(&a+1);
    });
    dbg!(&a);
    handler.join().unwrap();
}

It's clear that the spawned thread doesn't outlive the main function, so why does it happen? Type system limitation?

ababo
  • 1,490
  • 1
  • 10
  • 24

1 Answers1

1

Compiler is not smart enough for that, use scope():

fn main() {
    let a = 1;

    std::thread::scope(|s| {
        s.spawn(|| {
            dbg!(&a + 1);
        });
    });

    dbg!(&a);
}
Stargateur
  • 24,473
  • 8
  • 65
  • 91
  • It works for OS threads, thanks. Could you please suggest the similar thing for tokio or actix_web? – ababo Sep 18 '22 at 17:37
  • @ababo that way different, in async this is probably an anti pattern, can you provide a snipped of what you would want (make a new question maybe) – Stargateur Sep 18 '22 at 17:39
  • Exactly the same structure, just different spawn with `async {}`. – ababo Sep 18 '22 at 17:40
  • @ababo well I don't know what to answer except don't do this pattern in async, it's simply don't make sense and I think that mostly impossible, notice you can like thread, retrieve the value return by a async task with the join handle. Without usecase/practical question I can help more, I can only give random help like in async we use channel to send message we don't share data, https://docs.rs/tokio/latest/tokio/sync/mpsc/index.html. – Stargateur Sep 18 '22 at 17:49
  • No problem, I can use 'async move' and clone the variable. Thank you. – ababo Sep 18 '22 at 18:08
  • @ababo You cannot have scoped async tasks because of issues with cancellation. – Chayim Friedman Sep 19 '22 at 04:54