For example, I have a structure and implementation, and want to run a method of this struct in a new thread from other method of the same struct.
Like here:
use std::thread;
struct App {
// Different data
}
impl App {
fn method1(&self) {
...
}
fn method2(&self) {
thread::spawn(| | {
self.method1(); // It does not work
});
}
}
How to correctly send a pointer to struct to other thread from the method of the same struct?
Generally, the correct way to do this is to split your struct into multiple structs, one per thread. This article talks about this kind of thing in the context of actors, but the same principle applies whenever you want to access stuff from several threads.
However, you can't do that from inside of a method taking &self, because that &self is only loaned to the method temporarily until the method returns on the current thread. The loan doesn't last long enough for another call to finish elsewhere (if you just call another method while blocking the current method waiting on it, you don't gain anything).
It could be made to work with self: Arc<Self>, or by calling methods on some other self-contained or Arc-wrapped object and not &self. Generally you'd rather make the callers spawn multiple calls themselves.
And of course you can't do that with &mut self, because mut is exclusive, and you can't have two threads having exclusive access to one thing. In such cases you'd use Mutex or Atomic* types, but with caution that they may destroy any benefit of using threads.