【问题标题】:How to use thrust::copy_if using pointers [closed]如何使用指针使用推力::copy_if [关闭]
【发布时间】:2021-02-04 10:42:37
【问题描述】:

我正在尝试使用指针将数组的非零元素复制到不同的数组。我尝试在thrust copy_if: incomplete type is not allowed 中实现该解决方案,但结果数组中的值为零。这是我的代码: 这是谓词函子:

struct is_not_zero
{
    __host__ __device__
    bool operator()( double x)
    {
        return (x != 0);
    }
};

这就是使用copy_if函数的地方:

double out[5];
thrust::device_ptr<double> output = thrust::device_pointer_cast(out);
    double *test1;

    thrust::device_ptr<double> gauss_res(hostResults1);

   thrust::copy_if(thrust::host,gauss_res, gauss_res+3,output, is_not_zero());

    test1 = thrust::raw_pointer_cast(output);
    
    for(int i =0;i<6;i++) {
        cout << test1[i] << " the number " << endl;
    }

其中 hostresult1 是内核的输出数组。

【问题讨论】:

  • device_ptrthrust::host 执行策略一起使用是没有意义的。
  • @RobertCrovella 当我删除推力::主机时出现此错误:在抛出 'thrust::system::system_error what() 的实例后调用终止:copy_if 无法同步:非法内存访问遇到了
  • 您无法使用主机数据创建device_ptr,因此您显示的前两行代码已损坏:double out[5]; thrust::device_ptr&lt;double&gt; output = thrust::device_pointer_cast(out); 不要混淆主机数据和主机算法,带有设备数据和设备算法。
  • @RobertCrovella 那么我应该在创建设备指针之前执行 cudaMalloc((void**)output) 吗?
  • 当您提供不完整的代码时,我只能猜测您要做什么。看看答案猜一猜。

标签: cuda thrust


【解决方案1】:

您犯了 cmets 中讨论的各种错误,并且您没有提供完整的代码,因此无法说明您所犯的所有错误。一般来说,您似乎混淆了设备和主机活动以及指针。这些通常应在算法中保持分开并单独处理。例外情况是从设备复制到主机,但这不能用thrust::copy 和原始指针来完成。您必须使用矢量迭代器或正确修饰的推力设备指针。

这是一个基于您所展示内容的完整示例:

$ cat t66.cu
#include <thrust/copy.h>
#include <iostream>
#include <thrust/device_ptr.h>
struct is_not_zero
{
    __host__ __device__
    bool operator()( double x)
    {
        return (x != 0);
    }
};


int main(){
    const int ds = 5;
    double *out, *hostResults1;
    cudaMalloc(&out, ds*sizeof(double));
    cudaMalloc(&hostResults1, ds*sizeof(double));
    cudaMemset(out, 0, ds*sizeof(double));
    double test1[ds];
    for (int i = 0; i < ds; i++) test1[i] = 1;
    test1[3] = 0;
    cudaMemcpy(hostResults1, test1, ds*sizeof(double), cudaMemcpyHostToDevice);
    thrust::device_ptr<double> output = thrust::device_pointer_cast(out);

    thrust::device_ptr<double> gauss_res(hostResults1);

    thrust::copy_if(gauss_res, gauss_res+ds,output, is_not_zero());
    cudaMemcpy(test1, out, ds*sizeof(double), cudaMemcpyDeviceToHost);
    for(int i =0;i<ds;i++) {
        std::cout << test1[i] << " the number " << std::endl;
    }
}
$ nvcc -o t66 t66.cu
$ ./t66
1 the number
1 the number
1 the number
1 the number
0 the number

【讨论】:

    猜你喜欢
    • 2013-11-03
    • 2018-03-27
    • 1970-01-01
    • 2020-07-27
    • 1970-01-01
    • 2013-04-22
    • 1970-01-01
    • 2015-12-06
    • 2010-09-14
    相关资源
    最近更新 更多