多个线程将数据发送到数组C++

Multiple threads to data to array C++

本文关键字:数组 C++ 数据 线程      更新时间:2023-10-16

我使用for循环来创建给定数量的线程,每个线程都对我的部分积分进行近似,我希望他们将数据返回给数组,以便稍后我可以对其进行求和(如果我想得对,我不能在每个线程中只求和+=,因为它们会发生冲突(,一切都很好,直到我想从每个线程获取数据的那一刻,我得到了错误:

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

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

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

你必须做的步骤是:

  • 准备N承诺

  • 启动N-1线程

  • 从主调用thd

  • 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,size,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;