0

I'm quite new to Rust, so I've encountered a few things I'm not used to. One issue that's causing me some grief is related to threads.

I would like to spawn a thread that executes a struct's method, but I'm not able to because the method needs to have a 'static lifetime. I'd prefer the method (and by extension the struct) didn't have a 'static lifetime.

If I know for certain that the thread will exit before the struct's instantiated value is dropped, is there a way to communicate this with Rust? In other words, can I tell Rust that I can guarantee the value will not have been dropped until after the thread exits? Or perhaps is there a way to pass a lifetime to a thread?

If none of this is possible, what can be done instead? I've looked into making the code asynchronous instead, but haven't had any success in fixing the issues described above.

If the method and struct must have a 'static lifetime, how might I go about appropriately specifying this?

Here's a simplified example of the problem:

pub struct Thing {
    value: i32,
}

impl Thing {
    pub fn new(value: i32) -> Thing {
        Thing {
            value,
        }
    }

    fn in_thread(&self) {
        println!("in thread");
        // do things that block the thread
    }

    pub fn spawn_thread(&self) {
        std::thread::spawn(move || {
            self.in_thread();           // problem occurs here
        });
    }
}
Jonas
  • 121,568
  • 97
  • 310
  • 388
WKHAllen
  • 51
  • 2
  • 3
  • 9
  • Note that this example (if you do anything with `self` in `in_thread`) is unsound -- because you didn't call `join` on the handle, `self` could be dropped while the child thread is still running. This is exactly the problem that scoped threads prevent by making it impossible to forget to call `join`. – trent Sep 19 '20 at 20:22
  • I believe this answers my question, thank you. And yes I would have included a call to `join` but didn't for the sake of simplicity. – WKHAllen Sep 19 '20 at 20:31

1 Answers1

0

If none of this is possible, what can be done instead? I've looked into making the code asynchronous instead, but haven't had any success in fixing the issues described above.

I wouldn't recommend to pass data via references to other threads. Instead, try to design your program so that the thread can own the data. You can do this by either move in the data when spawning a thread, alternatively, you may want to pass data via a Channel.

Jonas
  • 121,568
  • 97
  • 310
  • 388