【问题标题】:c++ 11 threads in iteration loop timec++ 11个线程在迭代循环时间
【发布时间】:2015-08-27 22:46:32
【问题描述】:

我有一个迭代时间的算法,这意味着它与时间步长一致。它使用两个主要功能,因为不共享数据而很容易实现多线程。每次迭代都会调用这两个函数。实际上我在每次迭代时都创建了两个新线程,但它并没有改善时间,所以是否可以只创建一次线程,在开始迭代之前,然后 func1 总是在线程 1 中运行,而 func2 在线程 2 中运行每一步?所以我会节省线程处理等的时间......

谢谢

巴勃罗

【问题讨论】:

  • 你能在你的问题中显示一个代码示例吗?
  • 不太清楚你在问什么。是的,您可以一次创建 2 个线程,并让它们分别运行一个函数。
  • @Pablo:请记住,每次迭代启动和停止线程会花费大量时间。开销和大量上下文切换是您的敌人。尝试在迭代开始之前启动一堆线程,让你的线程连续执行一堆任务。但正如 Jason 已经问过的,一些代码会更有帮助。

标签: c++ multithreading


【解决方案1】:

嗯,它是一个有限元代码。但它是一个具有相似结构的伪代码。

 #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;
}

基本上,我只想创建线程 t1 和 t2 一次,然后总是 t1 执行 func1 和 t2 执行 func2。

谢谢

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-23
    • 2019-02-12
    • 1970-01-01
    • 2016-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-11
    相关资源
    最近更新 更多