How to run different methods of "struct" in different threads?

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.

1 Like

You can use scoped threads or rayon::join to run multiple calls on different 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.

3 Likes

Thank you!

self: Arc worked for me:

fn method2(self: Arc<Self>) {
    let aself = self.clone();
    thread::spawn(| | {
        aself.method1();        // Works
    });
}

The fields inside the struct that needed to modify from threads, I've wrapped by Arc<Mutex<...>>

You do not need to wrap individual fields in an Arc if the entire struct is in an Arc

1 Like

Yes, you are right, thanks.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.