Threads and stdlib Random

What’s the state of the Random stdlib and thread safety? I thought I remembered some notes on this from several Julia releases back, but the Random docs have almost nothing on the topic. The only reference to threads is for seed!:

If rng is not specified, it defaults to seeding the state of the shared thread-local generator.

Is rand(rng) threadsafe? What about rand(Random.GLOBAL_RNG)? What is Random.GLOBAL_RNG, since it’s not a MersenneTwister? Thanks!

no. basically you should think that when you do rand() in thread, each thread has its own rng. Which makes rand() thread-safe.


It’s a special object (of singleton type Random._GLOBAL_RNG) that turns into a per-thread MersenneTwister by calling Random.default_rng().


I made a PR to add some basic info: document thread safety for RNGs by stevengj · Pull Request #40109 · JuliaLang/julia · GitHub


This works as well, I like I can choose to have a (a) random script, (b) deterministic script with individually random functions (same run of the script/model, same output) or (c) deterministic functions (same call with same input, same output), but it requires Julia >= 1.5: