将变量作为C ++中的线程引用传递时的外部错误

时间:2015-10-26 15:27:38

标签: c++ multithreading concurrency

我正在尝试制作一些线程来同时计算平均值,最小值,最大值和标准差。

像这样(T是100大小的双数组):

P[0] = thread(&average, T, ref(average));
P[0].join();
P[1] = thread(&maxmin, T, ref(max), ref(min)),
P[2] = thread(&standardDev, T, ref(stdDev),ref(average));

P[1].join();
P[2].join();

在方法中:

void average(double* T, double &average) {
double sum=0.0;
for(int i=0;i<100;i++){
    sum +=T[i];
}
average = sum/100;  
}

然后我用:

编译它
g++ -pthread -std=c++11 (filename) -o (name)

但它失败并显示此错误:

In file included from /usr/include/c++/4.8/thread:39:0,
             from ejercicio_4.cpp:2:
/usr/include/c++/4.8/functional: In instantiation of ‘struct std::_Bind_simple<double*(double*, std::reference_wrapper<double>)>’:
/usr/include/c++/4.8/thread:137:47:   required from ‘std::thread::thread(_Callable&&, _Args&& ...) [with _Callable = double*; _Args = {double (&)[100], std::reference_wrapper<double>}]’
ejercicio_4.cpp:89:40:   required from here
/usr/include/c++/4.8/functional:1697:61: error: no type named ‘type’ in ‘class std::result_of<double*(double*, std::reference_wrapper<double>)>’
       typedef typename result_of<_Callable(_Args...)>::type result_type;
                                                             ^
/usr/include/c++/4.8/functional:1727:9: error: no type named ‘type’ in ‘class std::result_of<double*(double*, std::reference_wrapper<double>)>’
         _M_invoke(_Index_tuple<_Indices...>)
         ^

我有g ++ 4.8,所以应该使用线程,我不知道是什么导致了这个错误。

提前致谢。

1 个答案:

答案 0 :(得分:2)

在第一行有一个拼写错误或名称冲突,您将第二个参数作为函数名称(average)而不是目标变量的名称传递。你可能想写的是:

double avg;
P[0] = thread(&average, T, ref(avg));