std :: threads构造函数参数错误

时间:2014-12-17 18:55:14

标签: c++ multithreading templates c++11 move

我不是一个优秀的C ++程序员,但目前正在使用C ++的一些功能来清理我的C代码的脏部分。 g ++编译器抱怨threads[i] = thread(split, i, sums[i], from, to, f, nThreads);。请帮我找到问题。

// mjArray只是一个瘦的类而不是std :: vector,在我的情况下太重了。

#include <cstdio>
#include <cmath>
#include <ctime>
#include <thread>
using namespace std;

template<typename T>
class mjArray {
private:
    T* _array;
    int _length;

public:
    mjArray(int length) {
        _array = new T[length];
        _length = length;
    }

    mjArray(int length, T val) {
        _array = new T[length];
        _length = length;
        for (int i = 0; i < length; ++i) {
            _array[i] = val;
        }
    }

    ~mjArray() {
        delete[] _array;
    }

    T& operator[](int i) {
        return _array[i];
    }

    int length() {
        return _length;
    }
};

void split(int n, double& sum, int from, int to, double (*f)(double), int nThreads) {
    for (int i = from + n; i <= to; i += nThreads) {
        sum += f(i);
    }
}

double sigma(int from, int to, double (*f)(double), int nThreads) {
    double sum = 0.0;
    mjArray<double> sums(nThreads, 0.0);
    mjArray<thread> threads(nThreads);
    for (int i = 0; i < nThreads; ++i) {
        threads[i] = thread(split, i, sums[i], from, to, f, nThreads);
    }
    for (int i = 0; i < nThreads; ++i) {
        threads[i].join();
        sum += sums[i];
    }
    return sum;
}

double f(double x) {
    return (4 / (8 * x + 1) - 2 / (8 * x + 4) - 1 / (8 * x + 5) - 1 / (8 * x + 6)) / pow(16, x);
}

int main(void) {
    for (int i = 1; i <= 4; ++i) {
        time_t start = clock();
        double pi = sigma(0, 1000000, f, i);
        time_t end = clock();
        printf("pi = %.10f; nThreads = %d; elapsed = %.3fs\n", pi, i, (double)(end - start) / CLOCKS_PER_SEC);
    }
    return 0;
}

1 个答案:

答案 0 :(得分:5)

#include <functional>

threads[i] = thread(split, i, std::ref(sums[i]), from, to, f, nThreads);
//                            ~~~~~~~~^

理由:

std::thread存储传入其构造函数的参数的衰减副本,然后std::move d初始化在该新线程中运行的仿函数对象的参数。如果引用失败,因为您无法使用xvalue初始化非const左值引用(double& split函数期望的double)(更不用说它是完全不同的{{1实例,而不是传递给thread's构造函数的实例。)

解决方案是使用辅助函数std::reference_wrapper<T>返回的std::ref 它将您的引用包装在可复制对象中,该对象成功地将您的引用传输到新创建的线程。