线程安全的随机数生成
(金庆的专栏)
* rand()不可重入
* 用线程专用存储保存随机数生成器
* 自动设置随机种子为设备随机数
* 线程退出时,自动析构生成器
typedef boost::random::mt19937 Generator;
static Generator & GetGen()
{
static boost::thread_specific_ptr<Generator> s_pRng;
Generator * pRng = s_pRng.get();
if (pRng) return *pRng;
s_pRng.reset(new Generator);
s_pRng->seed(boost::random_device()());
return *s_pRng.get();
}
Uint32 Rand32()
{
return GetGen()();
}
// Random in [nFrom, nTo].
int Rand(int nFrom, int nTo)
{
if (nFrom > nTo)
boost::swap(nFrom, nTo);
BOOST_ASSERT(nFrom <= nTo);
boost::random::uniform_int_distribution<int> dist(nFrom, nTo);
return dist(GetGen());
}