将cuda数组传递给thrust :: inclusive_scan

时间:2015-10-15 19:07:48

标签: cuda thrust

我可以在cpu上使用inclusive_scan作为数组,但是可以在gpu上使用数组吗? (评论是我知道的方式,但我不需要)。或者,是否还有其他简单的方法可以对设备内存中的阵列执行包容性扫描?

代码:

#include <stdio.h>
#include <stdlib.h> /* for rand() */
#include <unistd.h> /* for getpid() */
#include <time.h> /* for time() */
#include <math.h>
#include <assert.h>
#include <iostream>
#include <ctime>
  #include <thrust/scan.h>
#include <cuda.h>



#ifdef DOUBLE
 #define REAL double
 #define MAXT 256
#else
 #define REAL float
 #define MAXT 512
#endif

#ifndef MIN
#define MIN(x,y) ((x < y) ? x : y)
#endif

using namespace std;

bool errorAsk(const char *s="n/a")
{
cudaError_t err=cudaGetLastError();
if(err==cudaSuccess)
    return false;
printf("CUDA error [%s]: %s\n",s,cudaGetErrorString(err));
return true;
};

double *fillArray(double *c_idata,int N,double constant) {
    int n;
    for (n = 0; n < N; n++) {
            c_idata[n] = constant*floor(drand48()*10);

    }
return c_idata;
}

int main(int argc,char *argv[])
{
    int N,blocks,threads;
    N = 100;
    threads=MAXT;
    blocks=N/threads+(N%threads==0?0:1);

    double *c_data,*g_data;

    c_data = new double[N];
    c_data = fillArray(c_data,N,1);
    cudaMalloc(&g_data,N*sizeof(double));

    cudaMemcpy(g_data,c_data,N*sizeof(double),cudaMemcpyHostToDevice);
    thrust::inclusive_scan(g_data, g_data + N, g_data); // in-place scan
    cudaMemcpy(c_data,g_data,N*sizeof(double),cudaMemcpyDeviceToHost);

//        thrust::inclusive_scan(c_data, c_data + N, c_data); // in-place scan

    for(int i = 0; i < N; i++) {
            cout<<c_data[i]<<endl;
    }
}

1 个答案:

答案 0 :(得分:4)

如果您阅读thrust quick start guide,您会找到一个处理建议&#34; raw&#34;设备数据:使用thrust::device_ptr

  

你可能想知道当&#34; raw&#34;指针用作Thrust函数的参数。与STL一样,Thrust允许这种用法,它将调度算法的主机路径。如果有问题的指针实际上是指向设备内存的指针,那么在调用函数之前,你需要用thrust :: device_ptr来包装它。

要修复代码,您需要

#include <thrust/device_ptr.h>

并使用以下两行替换现有的thrust::inclusive_scan来电:

thrust::device_ptr<double> g_ptr = thrust::device_pointer_cast(g_data);
thrust::inclusive_scan(g_ptr, g_ptr + N, g_ptr); // in-place scan

另一种方法是使用推力execution policies并修改你的调用:

thrust::inclusive_scan(thrust::device, g_data, g_data + N, g_data);

还有其他各种可能性。