Is mersenne twister thread safe for cpp

前端 未结 2 1772
[愿得一人]
[愿得一人] 2021-01-18 08:59
#include 

int f() {

    std::random_device seeder;
    std::mt19937 engine(seeder());
    std::uniform_int_distribution dist(1, 6);

    r         


        
2条回答
  •  迷失自我
    2021-01-18 09:38

    Can multiple threads call this function safely? Is the function thread safe?

    This particular function is thread safe. It is OK to create random number generators, engines and distributions, and call generate a number in a function local engine in multiple threads.

    Of course, the output from multiple threads can be interleaved since cout isn't synchronized.

    Do I need to initialize the engine in every function call

    That is what your function does, and while that does guarantee thread safety, it is the opposite of what you need to do. Initializing the engine every time will make the "randomness" sequence directly depend on the seeder. And it of course adds overhead to initialize the engine.

    or would it be better to put the first two lines (seeder and engine) in a class constructor?

    You can use a wrapper class, but you don't have to. That is orthogonal to whether you create a new engine instance in every function call. As long as each function call uses same engine as previous calls, there is no problem with randomness in that regard.

    But using same engine across threads is indeed not thread safe. You could instead use one engine in each thread - or protect a shared engine with a mutex, but that has significant overhead.

提交回复
热议问题