0

I am new to multithreaded programming and I am unable to execute following code:

use std::thread;

struct Test;

impl Test {
    pub fn foo(&self) {
        for i in 0..5 {
            thread::spawn(|| { self.bar(); });
        }
    }
    
    pub fn bar(&self) {
        println!("bar");
    }
}


fn main() {
    let t = Test{};
    t.foo()
}

I receive following error:

self has an anonymous lifetime '_ but it needs to satisfy a 'static lifetime requirement

I am assuming this happens because thread does not know if the object self refers to does not get deleted during the execution of the thread. Is there any way to somehow execute this code? Or do I need my methods to have static lifetimes? (if such thing is even possible)

Here is the playground link.

pretzelhammer
  • 13,874
  • 15
  • 47
  • 98
Ach113
  • 1,775
  • 3
  • 18
  • 40
  • 1
    [Here's an example using `crossbeam` to solve your problem, as suggested in the linked question.](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=0aa2430b6db6afd95ffbacc54ccb4936) If this does not answer your question, please [edit] it to explain how it's different. Thanks! – trent Oct 23 '20 at 16:57
  • @trentcl Would it be possible to do something similar with only `std` ? – Ach113 Oct 23 '20 at 17:17
  • Not safely, no, because standard threads can outlive their parent, as the other question's answer also mentions. You can fix some similar problems [using `Arc`](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=02b44c43daf78db4709cfc9b1fbb526a) but in this case it does not have the same (or deterministic) output, precisely because the spawned threads are not joined before the main thread ends. – trent Oct 23 '20 at 17:37

0 Answers0