使用 boost 的 mt19937 产生器。
#include <boost/thread/thread.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/random.hpp>
#include <iostream>
boost::mutex io_mutex;
#define __NR_gettid 186
class ABCD {
public:
void count(int seed, const char* pcszStr) {
//产生随机数
boost::mt19937 rng(seed);
//这里要括起来,因为有个范围锁。
{
boost::mutex::scoped_lock lock(io_mutex);
std::cout << "min:" << rng.min() << " max:" << rng.max() << std::endl;
std::cout << "1:" << rng() << " 2:" << rng() << " 3:" << rng() << std::endl;
}
//产生指定范围均匀分布的随机数
boost::uniform_int<> dist(1, 999);
boost::variate_generator<boost::mt19937&, boost::uniform_int<> > gen(rng, dist);
for (int i = 0; i < 10; ++i) {
boost::mutex::scoped_lock lock(io_mutex);
std::cout<<"[" << syscall(__NR_gettid) << "]" << pcszStr << ": " << gen() << std::endl;
}
}
void startthread() {
boost::thread thrd1(&ABCD::count,this,77,"hello");
boost::thread thrd2(&ABCD::count,this,88,"world");
thrd1.join();
thrd2.join();
return;
}
};
int main(int argc, char* argv[])
{
ABCD aa;
aa.startthread();
return 0;
}