c++ - 从多个线程使用 stdlib 的 rand()

我有几个线程都运行相同的功能。在每一个中,它们都会多次生成不同的随机数。我们试图通过将 srand(time(0)) 放在函数的开头来做到这一点,但似乎它们都得到了相同的数字。

我们是否需要每个程序只调用一次 srand(time(0)),即在 main 的开头(例如),在每个程序的开头被多次调用的函数,还是别的什么?

最佳答案

srand()种子随机数生成器。您应该只需要在启动期间调用一次 srand(time(NULL))

也就是说,文档指出:

The function rand() is not reentrant or thread-safe, since it uses hidden state that is modified on each call. This might just be the seed value to be used by the next call, or it might be something more elaborate. In order to get reproducible behaviour in a threaded application, this state must be made explicit. The function rand_r() is supplied with a pointer to an unsigned int, to be used as state. This is a very small amount of state, so this function will be a weak pseudo-random generator. Try drand48_r(3) instead.

上面强调的部分可能是你所有线程得到相同数字的原因。

https://stackoverflow.com/questions/6161322/

相关文章:

c++ - 我们可以有一个虚拟静态方法吗? (c++)

c++ - 打包结构是可移植的吗?

c++ - 存储未初始化的 STL vector ?

c++ - 为什么我们在 C++ 中使用 std::function 而不是原来的 C 函数指针?

c++ - 在 getter 函数中返回 const 引用或拷贝?

c++ - 为什么这个包含 rand() 的 C++11 代码多线程比单线程慢?

c++ - 访问类中定义的 friend 功能

c++ - C 和 C++ 中的多字 rune 字

c++ - 对于所有对象类型 T,sizeof(T) >= alignof(T) 是否总是如此?

c++ - std::vector 是 `user-defined type` 吗?