我是 GPU 和 CUDA 编程的新手。我正在尝试将设备上动态分配的结构化数据从设备复制到主机。我从 GPU 编程指南中修改了一个简单的代码。编译代码时我没有收到任何错误,但我唯一有问题的是输出错误,即“0”。这是代码:
#include <stdlib.h>
#include "cuda_runtime.h"
#include "device_launch_parameters.h"
#include <stdio.h>
typedef struct Point
{
int2 pt;
};
#define NUMOFBLOCKS 1
#define THREDSPERBLOCK 16
__device__ Point* pnt[NUMOFBLOCKS];
Point dataptr_h[NUMOFBLOCKS][THREDSPERBLOCK];
__global__ void allocmem()
{
if (threadIdx.x == 0)
pnt[blockIdx.x] = (Point*)malloc(1*blockDim.x * sizeof(Point));
__syncthreads();
}
__global__ void usemem()
{
Point* ptr = pnt[blockIdx.x];
if (ptr != NULL)
{
ptr[threadIdx.x].pt.x = threadIdx.x;
ptr[threadIdx.x].pt.y = threadIdx.x;
printf("Ptr = %d\t", ptr[threadIdx.x].pt.x);
}
}
__global__ void freemem()
{
Point* ptr = pnt[blockIdx.x];
if (ptr != NULL)
printf("Block %d, Thread %d: final value = %d\n", blockIdx.x, threadIdx.x, ptr[threadIdx.x]);
if (threadIdx.x == 0)
free(ptr);
}
int main()
{
Point* d_pt[NUMOFBLOCKS];
for (int i = 0 ; i < NUMOFBLOCKS; i++)
cudaMalloc(&d_pt[i], sizeof(Point)*16);
// Allocate memory
allocmem<<< NUMOFBLOCKS, THREDSPERBLOCK >>>();
// Use memory
usemem<<< NUMOFBLOCKS, THREDSPERBLOCK >>>();
cudaMemcpyFromSymbol(d_pt, pnt, sizeof(d_pt));
cudaMemcpy(dataptr_h, d_pt, sizeof(dataptr_h), cudaMemcpyDeviceToHost);
for (int j = 0 ; j < 1; j++)
for (int i = 0 ; i < 16; i++)
{
printf("\nPtr_h(%d,%d)->X = %d\t", j, i, dataptr_h[j][i].pt.x);
printf("Ptr_h(%d,%d)->Y = %d", j, i, dataptr_h[j][i].pt.y);
}
freemem<<< NUMOFBLOCKS, THREDSPERBLOCK >>>();
cudaDeviceSynchronize();
return 0;
}
代码的输出是:
Ptr_h(0,0)->X = 0 Ptr_h(0,0)->Y = 0
Ptr_h(0,1)->X = 0 Ptr_h(0,1)->Y = 0
Ptr_h(0,2)->X = 0 Ptr_h(0,2)->Y = 0
Ptr_h(0,3)->X = 0 Ptr_h(0,3)->Y = 0
Ptr_h(0,4)->X = 0 Ptr_h(0,4)->Y = 0
Ptr_h(0,5)->X = 0 Ptr_h(0,5)->Y = 0
Ptr_h(0,6)->X = 0 Ptr_h(0,6)->Y = 0
Ptr_h(0,7)->X = 0 Ptr_h(0,7)->Y = 0
Ptr_h(0,8)->X = 0 Ptr_h(0,8)->Y = 0
Ptr_h(0,9)->X = 0 Ptr_h(0,9)->Y = 0
Ptr_h(0,10)->X = 0 Ptr_h(0,10)->Y = 0
Ptr_h(0,11)->X = 0 Ptr_h(0,11)->Y = 0
Ptr_h(0,12)->X = 0 Ptr_h(0,12)->Y = 0
Ptr_h(0,13)->X = 0 Ptr_h(0,13)->Y = 0
Ptr_h(0,14)->X = 0 Ptr_h(0,14)->Y = 0
Ptr_h(0,15)->X = 0 Ptr_h(0,15)->Y = 0
我能做些什么来解决这个问题?