多线程数据到数组C ++

我正在使用for循环创建给定数量的线程,每个线程都使我的整数部分近似,我希望它们将数据返回给数组,以便稍后我可以总结一下(如果我认为正确的话) ,我不能只在每个线程中使sum + =,因为它们会发生冲突),一切正常,直到我想从每个线程中获取数据时,我都会出错:

calka.cpp:49:33: error: request for member 'get_future' in 'X',which is of non-class type 'std::promise<float>[(N + -1)]'

代码:

#include <iostream> //cout  
#include <thread> //thread
#include <future> //future,promise
#include <stdlib.h> //atof
#include <string> //string
#include <sstream> //stringstream

using namespace std;

// funkcja 4x^3 + (x^2)/3 - x + 3
// całka x^4 + (x^3)/9 - (x^2)/2 + 3x 

void thd(float begin,float width,promise<float> & giveback)
{   
    float x = begin + 1/2 * width;
    float height = x*x*x*x + (x*x*x)/9 - (x*x)/2 + 3*x ; 
    float outcome = height * width;
    giveback.set_value(outcome);    

    stringstream ss;
    ss << this_thread::get_id();
    string output = "thread #id: " + ss.str() + "  outcome" + to_string(outcome);

    cout << output << endl;

}

int main(int argc,char* argv[])
{

    int sum = 0;
    float begin = atof(argv[1]);
    float size = atof(argv[2]);
    int N = atoi(argv[3]);
    float end = begin + N*size;

    promise<float> X[N-1];



    thread t[N];

    for(int i=0; i<N; i++){
        t[i] = thread(&thd,begin,size,ref(X[i]));
        begin += size;
    }

    future<float> wynik_ftr = X.get_future();
    float wyniki[N-1];

    for(int i=0; i<N; i++){
        t[i].join();
        wyniki[i] = wynik_ftr.get();
    }
    //place for loop adding outcome from threads to sum
    cout << N;

    return 0;
}
lwr82545744 回答:多线程数据到数组C ++

请勿使用VLA-promise<float> X[N-1]。它是某些编译器的扩展,因此您的代码不可移植。请改用std::vector

似乎您想将积分计算拆分为N个线程。您创建了N-1个后台线程,并且thd线程执行了一次main的调用。在main中加入所有结果,因此 您不需要创建wyniki作为数组来存储每个线程的结果, 因为您要以串行方式收集这些结果-在main函数的for循环内。 因此,一个float wyniki变量就足够了。

您需要执行的步骤是:

  • 准备N诺言

  • 启动N-1线程

  • 从主通话thd

  • 加入并添加for循环中N-1个线程的结果

  • 加入并添加主线程结果

代码:

std::vector<promise<float>> partialResults(N);

std::vector<thread> t(N-1);

for (int i = 0; i<N-1; i++) {
    t[i] = thread(&thd,begin,size,ref(partialResults[i]));
    begin += size;
}

thd(begin,ref(partialResults[N-1]));
float wyniki = 0.0f;
for (int i = 0; i<N-1; i++) {
    t[i].join();
    std::future<float> res = partialResults[i].get_future();
    wyniki  += res.get();
}
std::future<float> res = partialResults[N-1].get_future(); // get res from main
wyniki += res.get();

cout << wyniki << endl;
本文链接:https://www.f2er.com/3135942.html

大家都在问