在C ++应用程序中应该多久调用一次srand()? [英] How often should I call srand() in a C++ application?

查看:138
本文介绍了在C ++应用程序中应该多久调用一次srand()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个C ++应用程序,该应用程序在不同的地方调用rand().我是否需要定期初始化srand()以确保rand()具有合理的随机性,或者足以在应用启动时对其调用一次?

I have a C++ application which calls rand() in various places. Do I need to initialize srand() regularly to ensure that rand() is reasonably random, or is it enough to call it once when the app starts?

推荐答案

如果只有一个线程,则一次.如果经常播种,实际上可能会破坏随机数的某些统计属性.如果您有多个线程,则根本不要使用rand,而要使用诸如drand48_r这样的线程安全的东西,它可以使您保持每个线程的状态(因此您可以为每个线程播种一次).

If you have only a single thread, seed once. If you reseed often, you might actually break some of the statistical properties of the random numbers. If you have multiple threads, don't use rand at all, but rather something threadsafe like drand48_r, which lets you maintain a per-thread state (so you can seed once per thread).

这篇关于在C ++应用程序中应该多久调用一次srand()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆