【发布时间】:2015-08-15 13:20:07
【问题描述】:
在下面的代码中,我在结构中有一个数组,我需要将它传递给内核函数。我似乎找不到正确的方法。我尝试查看 SO 上的其他帖子,但不太了解他们的方法。
在我的实际代码中,我接收到两个结构,作为指针,作为调用内核的函数的参数。因此,我需要将这些 'argument structs' 的内容复制到 'GPU memory structs' 并传递给内核。
#include <stdio.h>
#include <stdlib.h>
typedef struct{
int *pass;
int element;
}Pass;
__global__ void hello(int *a, int *b, Pass *p){
int i = blockIdx.x * blockDim.x + threadIdx.x;
if(i < *b)
a[i] = p -> pass[i] + p -> element;
}
int main(){
int *a_host, b_host = 5;
int *a_gpu, *b_gpu;
Pass *p, *p_gpu;
a_host = (int*)malloc(sizeof(int) * 5);
cudaMalloc(&a_gpu, 5 * sizeof(int));
cudaMalloc(&b_gpu, sizeof(int));
cudaMemcpy(b_gpu, &b_host, sizeof(int), cudaMemcpyHostToDevice);
p = (Pass*)malloc(sizeof(Pass));
p -> pass = (int*)malloc(5 * sizeof(int));
for(int i = 0;i < 5;i++)
p -> pass[i] = i;
p -> element = 5;
cudaMalloc(&p_gpu, sizeof(Pass));
cudaMemcpy(p_gpu, p, sizeof(Pass), cudaMemcpyHostToDevice);
int numBlocks = 1;
int threadPerBlock = 512;
hello<<<numBlocks, threadPerBlock>>>(a_gpu, b_gpu, p_gpu);
cudaMemcpy(a_host, a_gpu, 5 * sizeof(int), cudaMemcpyDeviceToHost);
int i;
for(i = 0;i < 5;i++)
printf("a[%d]: %d\n", i, a_host[i]);
cudaFree(p_gpu);
cudaFree(a_gpu);
cudaFree(b_gpu);
free(p);
free(a_host);
return(0);
}
【问题讨论】:
-
我得出结论,
c_host.sparseCount为零,或者其他一些意外的数字。我投票结束,因为您没有提供MCVE(SO expects for questions like these。 -
@RobertCrovella 那么除此之外逻辑是可靠的吗?
-
@MessyCoder:绝对不可能说。如果您需要帮助,请发布其他人可以编译和运行的最短、最简单、完整示例,该示例会显示问题。否则你不会在这里走得很远
-
kerne 启动后的所有
cudaMemcpy调用都完全中断,并且犯了与您在上一个问题中完全相同的错误(albiet in reverse),以及非常严重的缓冲区溢出。 -
@talonmies 我现在更新了这个问题。请看一看。