简体   繁体   中英

c++ 11 threads in iteration loop time

I have an algorithm who iterate though time, it means it goes witth time steps. It is using two main functions who are easily multithreading because not share data. Both functins are called in every iteration. Actually i am creating two new thread at every iteration, but it is not improving the times, so is it possible create the threads only one time , before to begin the iterations and then func1 allways run in thread 1 and func2 run in thread 2 in every time step? so i would save the time in threading process etc...

Thanks

Pablo

well, it is a finite element code. But it is a dummy code who has similar structure.

 #include <iostream>
 #include <math.h>
 #include <vector>

 #include <thread>
using namespace std;

class Rectangle {
    double width, height;
  public:
    void set_values (double,double);
    double area() {return (width*height*sin(width)*cos(height))*(width*height*sin(width)*cos(height));}
};

void Rectangle::set_values (double x, double y) {
  width = x;
  height = y;
}

void func1(vector<Rectangle>& poli1)
{
    double suma1=0;
    double suma11=0;
    for ( int i =0; i<10000; i++){
        suma1 += poli1[i].area()/double(i+1);
        suma11++;
    }
}

void func2(vector<Rectangle>& poli2)
{
    double suma2=0;
    double suma22=0;
    for ( int j =0; j<10000; j++){
        suma2 += poli2[j].area()/double(j+1);
        suma22++;
    }
}

int main () {

int i,k;
vector<Rectangle> poli1;
vector<Rectangle> poli2;
vector<Rectangle> poli3;
for ( i =0; i<10000; i++){
  Rectangle rect;
  rect.set_values (3,4);
  poli1.push_back(rect);
}
for ( i =0; i<10000; i++){
  Rectangle rect;
  rect.set_values (3,4);
  poli2.push_back(rect);
}

for ( k=0; k<50000; k++){
    std::thread t1(func1,ref(poli1));
    t1.join();
    std::thread t2(func2,ref(poli2));
    t2.join();

}
  return 0;
}

Basically, i would like to create threads t1 and t2 only one time and then allways t1 execute func1 and t2 execuete func2.

Thanks

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM