How does thread_rng() in the rand crate help me?

A random number generator use an internal state to generate the next number.
To be able to generate number from anywhere in your code, this state need to be acceded from anywhere.
In Rust to share a value across thread this value must be Sync and mechanical like Mutex are required to ensure the value is acceded by one thread at once.
thread_rng() using thread_local! will creates a new ThreadRng for each thread.
Since each thread have it's own ThreadRng there no need for synchronization mecanical.


Storing the ThreadRnd from thread_rng() is more efficient than random() in case you need to generate multiple values.

Here a playground generating 100 000 values using both methods:

with thread_rng: 477.564µs
with random: 655.909µs

(To be accurate we would have to make a real benchmark, but this demonstrate that thead_rnd is faster when you want a lot of values)

6 Likes