我试图使用指针将数组的非零元素复制到不同的数组中。我尝试在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是来自内核的输出数组。
发布于 2020-10-21 14:57:10
您正在进行注释中讨论的各种错误,并且没有提供完整的代码,因此不可能说明您所犯的所有错误。一般来说,你似乎混淆了设备和主机的活动,以及指针。在算法中,它们通常应该保持分离,并单独处理。例外情况是从一个设备复制到另一个主机,但这不能用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 numberhttps://stackoverflow.com/questions/64464892
复制相似问题