Cuda::Thrust错误,提示“在抛出'thrust::system::system_error'实例后终止调用”。

4

What I write is ;

#include <thrust/system_error.h>
#include <thrust/host_vector.h>
#include <thrust/device_vector.h>
#include <thrust/sequence.h>
#include <thrust/transform.h>
#include <thrust/replace.h>
#include <thrust/copy.h>
#include <thrust/functional.h>
#include <iostream>
#include <cmath> //std:sqr

using namespace thrust;

// Kernel Code
template <class K>
struct sum_square_functor{
    __host__ __device__ K operator()(const K& x, const K& y)const{
        return pow(x-y,2);
    }
};

//Test code on CPU
//void perform_euclidean(){
//
//}


int main(){
    device_vector<float> p_vec(1 << 20);
    device_vector<float> q_vec(1 << 20);
    device_vector<float> r_vec(1 << 20);
    generate(p_vec.begin(), p_vec.end(), rand);
    generate(q_vec.begin(), q_vec.end(), rand);
    // Current Thrust's transformations supports 2 input vectors, so we use it
    transform(p_vec.begin(), p_vec.end(), q_vec.begin(), r_vec.begin(), sum_square_functor<float>());

    int sum = thrust::reduce(r_vec.begin(), r_vec.end(), (int)0, thrust::plus<float>());
    std::cout << "sqrt(" << sum  << ")=" << sqrt(sum) << std::endl;
    return 0;
}

完整的错误信息如下:

terminate called after throwing an instance of 'thrust::system::system_error'
  what():  unspecified launch failure

代码有什么问题?有任何想法吗?

我发现错误是由 generate() 引起的,但还是无法消除错误?

1个回答

4

rand是一个基于主机库的函数。您不能在设备代码中直接使用它。如果您尝试在设备向量上使用rand进行generate,则会创建一个设备代码内核,该内核正在尝试直接使用rand并失败。

相反,应在主机上创建这些向量并将其复制到设备上,或者使用与设备兼容的随机生成器(Thrust 有一些)。

您应该能够执行:

host_vector<float> h_p_vec(1 << 20);
host_vector<float> h_q_vec(1 << 20);
generate(h_p_vec.begin(), h_p_vec.end(), rand);
generate(h_q_vec.begin(), h_q_vec.end(), rand);
device_vector<float> p_vec = h_p_vec;
device_vector<float> q_vec = h_q_vec;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接