How do I generate thread-safe uniform random numbers?

前端 未结 5 656
渐次进展
渐次进展 2020-12-01 03:53

My program needs to generate many random integers in some range (int min, int max). Each call will have a different range. What is a good (preferably thread-safe) w

5条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-01 04:14

    I am a person from the future with the same problem. The accepted answer won't compile on MSVC 2013, because it doesn't implement thread_local (and using __declspec(thread) doesn't work because it doesn't like constructors).

    The memory leak in your solution can be moved off the heap by modifying everything to use placement new.

    Here's my solution (combined from a header and source file):

    #ifndef BUILD_COMPILER_MSVC
    thread_local std::mt19937 _generator;
    #else
    __declspec(thread) char _generator_backing[sizeof(std::mt19937)];
    __declspec(thread) std::mt19937* _generator;
    #endif
    template  inline type_float get_uniform(void) {
        std::uniform_real_distribution distribution;
        #ifdef BUILD_COMPILER_MSVC
            static __declspec(thread) bool inited = false;
            if (!inited) {
                _generator = new(_generator_backing) std::mt19937();
                inited = true;
            }
            return distribution(*_generator);
        #else
            return distribution(_generator);
        #endif
    }
    

提交回复
热议问题