A thread spawned via thread::spawn
can in theory outlive its parent thread. If the child thread could reference data from the parent thread, these reference would dangle (be invalid) when the parent thread stops. This is expressed as a 'static
bound on the closure given to thread::spawn
. The fact that you join
the thread in the same function is not understood by the compiler, so the restriction still holds.
You already tried to use an Arc
(presumably to get around this problem), but you are creating an Arc
of self
which is a reference already. So you are just putting a reference into an Arc
. That value does not satisfy the 'static
bound, that's why you are getting an error.
There are multiple ways to solve this problem, many depend on the overall architecture of your project. One of the easiest ways is to use scoped
from crossbeam
(or specifically, crossbeam_utils
):
use crossbeam_utils::thread;
impl MyTextOptions for MyText {
fn add(&self, text: String) {
thread::scope(|s| {
s.spawn(|_| {
let mut text_feed = self.my_text.lock().unwrap();
text_feed.push(text)
});
}).unwrap();
}
}
This is a fancy helper function that actually lets you borrow values from the parent scope by ensuring the child thread ends before the parent thread does.
Another solution would be to put the MyText
value into an Arc
(notably: by value, not by reference). Then you can clone this Arc
a bunch of times and send it to a new thread. But this means you cannot use methods that take &self
as receiver, but you have to solve it in another way.