Use Tokio Futures or Thread JoinHandling to run expensive computations?

Hi everyone.

I'm trying to increase the performance of one of my crates.
What I'm trying to do is parallelize the computation of two big prime numbers in order to increase the speed generation of both.

So I've seen two main options: Rust Thread JoinHandle or Tokio's Futures.

About Threads:

I've written the following, which consist of running two threads, each of them computing a BigUint (which is the output of the function gen_big_prime(). This does not compile and I still don't know why, because it's like the example that can be found on https://doc.rust-lang.org/1.27.2/std/thread/fn.spawn.html:
The error says binary operation *cannot be applied to type&() referring to p and q variables. I was expecting to get a BigUint from the thread after the join() and not &()

// ....... Some code
// Gen p q primal base 
        let p_comp = thread::spawn(|| {
            gen_big_prime(size, threshold.value);
        });
        let q_comp = thread::spawn(|| {
            gen_big_prime(size, threshold.value);
        });
        let p = p_comp.join().unwrap();
        let q = q_comp.join().unwrap();
        // Gen n and fi_n
        let n = &p * &q;
// Other operations .....

Even on this documentation page mentioned before, is said that It would probably be better to use Futures. But after taking a look to Tokio crate I've seen that I would need to implement Future trait for BigUint (which I think isn't the correct way to proceed in terms that I should not modify the crate I guess..)

So What do you think I should do? And why doesn't the code showed above compile?

Thanks.

Remove the semicolons to have the closures return the answers. Only need one thread spawn, second computation can be done on current thread.

You don't demonstrate anything that would benefit from Futures.

1 Like

you only need to spawn one sub-thread, for (say) p. You can calculate q on the main thread, which won't be doing anything anyway other than blocking on the joins. In other words, no need for a second spawn of a third thread. (No real harm in it either, if you prefer the symmetry, or find something else for the main thread to be doing in the meantime, of course)

1 Like

Thank you so much! That helped a lot!

1 Like