vendredi 8 novembre 2019

Multiple threads to data to array C++

I'm using for loop to create given ammount of threads, each one of them makes approximation of part of my integral, I want them to give that data back to array so later I can sum it up (if I think right, I can't just make sum += in each thread because they will collide), everything worked right, to the moment when I want to take that data from each thread, I get error:

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

code:

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

Aucun commentaire:

Enregistrer un commentaire