1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
| class Threaded_Sim_Class
{
private :
Rand_Gen gen;
size_t nbSimulations;
bool isMT;
struct MT_Data
{
Rand_Gen gen;
size_t nbSimulations;
Result result;
};
vector<boost::shared_ptr<MT_Data>> threadData;
size_t nbThreads;
public :
Threaded_Sim_Class(size_t _nbSimulations) //monothreading
:isMT(false),nbSimulations(_nbSimulations),gen()
{ }
Threaded_Sim_Class(size_t _nbSimulations,size_t _nbThreads) //multithread si _nbThreads>1
:nbThreads(_nbThreads),threadData(_nbThreads),nbSimulations(_nbSimulations),gen()
{
isMT=(nbThreads>1) ? true : false;
}
~Threaded_Sim_Class()
{}
double Pythagor(double _u)
{
return...;
}
Result getResult()
{
Result res;
if(!isMT)
{
for(size_t i=0; i<nbSimulations; ++i)
{
double tmp=Pythagor(gen.Next());
res.mean+=tmp;
res.var+=tmp*tmp;
}
res.mean/=nbSimulations; res.var=res.var/nbSimulations-(res.mean*res.mean);
}
else
{
for(size_t i=0; i<nbThreads; ++i)
{
threadData[i]=boost::shared_ptr<MT_Data>(new MT_Data);
threadData[i]->nbSimulations=nbSimulations/nbThreads;
threadData[i]->gen.skip(2*i* (nbSimulations/nbThreads));
}
boost::thread_group tg;
for(size_t i=0;i<nbThreads;++i)
{
tg.create_thread(boost::bind(&Threaded_Sim_Class::getResult,this,i));
}
tg.join_all();
for(size_t i=0;i<nbThreads;++i)
{
res.mean += threadData[i]->result.mean;
//res.var +=threadData[i]->result.var;
}
res.mean/=nbThreads;
}
return res;
}
void getResult(size_t _iThread)
{
boost::shared_ptr<MT_Data> td=threadData[_iThread]; //tempo
for(size_t i=0; i<td->nbSimulations; ++i)
{
double tmp=Pythagor(td->gen.Next(),td->gen.Next());
td->result.mean += tmp;
td->result.var +=tmp*tmp;
}
td->result.mean/=td->nbSimulations;
td->result.var=td->result.var/nbSimulations-(td->result.mean*td->result.mean);
}
}; |
Partager