轻云流风 2014-04-20 03:54
浏览 2279

cuda向设备端传递多个一维数组,并在核函数修改数组元素值

现在有多个一维数组,我想将他们拷贝到设备端修改他们的值,然后拷贝回host端,代码如下:
#include "cuda_runtime.h"
#include "device_launch_parameters.h"
#include "helper_cuda.h"
#include
#include
using namespace std;
#define N 10
global void gpuKernel(int ptr)
{

int tid=threadIdx.x;
int bid=blockIdx.x;
if (tid<N &&bid<N)
{

ptr[bid][tid]=N;

}
}
int main()
{
int **hptr,
hostArray;
int dptr,devArray;
hptr=new int [N];
cudaMalloc(&dptr,N*sizeof(int
));

hostArray=new int *[N];
devArray=new int *[N];
for (int i=0;i<N;i++)
{
hostArray[i]=new int[N];
for (int j=0;j<N;j++)
{
hostArray[i][j]=1;
}
}
for (int i=0;i<N;i++)
{
cudaMemcpy(devArray[i],hostArray[i],N*sizeof(int),cudaMemcpyHostToDevice);
hptr[i]=devArray[i];//保存每个数组的头指针
}

cudaMemcpy(dptr,hptr,N*sizeof(int*),cudaMemcpyHostToDevice);    
dim3 dimblock=N;
dim3 dimgrid =N;
gpuKernel<<<dimgrid,dimblock>>>(dptr);
for (int i=0;i<N;i++)
{       cudaMemcpy(hostArray[i],devArray[i],N*sizeof(int),cudaMemcpyDeviceToHost);      
}
for (int i=0;i<N;i++)
{
    for (int j=0;j<N;j++)
    {
        cout<<hostArray[i][j]<<",";
    }
    cout<<endl;

}
//free memory
for (int i=0;i<N;i++)
{
    delete []hostArray[i];
    cudaFree(devArray[i]);
}
cudaFree(dptr);
/*cudaFree(devArray);*/
delete[]hptr;
delete []hostArray;
delete[]devArray;   

return 0;

}
最终结果是元素值都为修改,纠结这个问题几天了,并且仔细拜读bendanban大神的博客http://blog.csdn.net/bendanban/article/details/7669624,可能自己理解有误,望各位大神指点

  • 写回答

0条回答

    报告相同问题?

    悬赏问题

    • ¥15 数值计算离散正交多项式
    • ¥30 数值计算均差系数编程
    • ¥15 redis-full-check比较 两个集群的数据出错
    • ¥15 Matlab编程问题
    • ¥15 训练的多模态特征融合模型准确度很低怎么办
    • ¥15 kylin启动报错log4j类冲突
    • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
    • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序
    • ¥15 onvif+openssl,vs2022编译openssl64
    • ¥15 iOS 自定义输入法-第三方输入法