如何使用推力:: copy_if使用指针

问题描述

我正在尝试使用指针将数组的非零元素复制到另一个数组。我尝试在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是内核的输出数组。

解决方法

您正在犯各种错误,如注释中所述,并且您没有提供完整的代码,因此无法陈述您正在犯的所有错误。一般而言,您似乎混淆了设备和主机活动以及指针。这些通常应分开保存,并在算法中分开处理。例外是从设备复制到主机,但这不能通过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,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,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

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...