gpt4 book ai didi

c++ - cudaMemcpyDeviceToHost() 失败

转载 作者:行者123 更新时间:2023-11-30 18:15:22 24 4
gpt4 key购买 nike

我有以下代码(假设所有内容都已正确定义):

#include "OurIncludes.h"
#include <ctime>

__global__ void kernel_testing(int *d_intersects, Circle *part1, Circle *part2)
{
int i = blockIdx.x * blockDim.x + threadIdx.x;
int j = blockIdx.y * blockDim.y + threadIdx.y;
if (i < 10 && j < 10) {
int index = i + j * 10;
d_intersects[index] = part1[i].intersect(part2[j]);
}
}


int main(void)
{
dim3 GRID(1, 1);
dim3 BLOCK(10, 10);

short randomNum;
RandObj randGenerator;
Circle* obj = new Circle[10];
Circle* obj2 = new Circle[10];
Circle *d_obj;
Circle *d_obj2;
int intersects[100];
int *d_intersects;

if (cudaSuccess != cudaMalloc((void **)&d_obj, sizeof(Circle) * 10)) {
fprintf(stderr, "Failed to allocate memory for d_result\n");
}
if (cudaSuccess != cudaMalloc((void **)&d_obj2, sizeof(Circle) * 10)) {
fprintf(stderr, "Failed to allocate memory for d_result\n");
}
if (cudaSuccess != cudaMalloc((void **)&d_intersects, sizeof(int) * 100)) {
fprintf(stderr, "Failed to allocate memory for d_result\n");
}
for (int i = 0; i < 10; i++) {
obj[i] = (*randGenerator.makeRandomCircle());
}

for (int i = 0; i < 10; i++) {
obj2[i] = (*randGenerator.makeRandomCircle());
}
size_t size = sizeof(Circle);
if (cudaSuccess != cudaMemcpy(d_obj, obj, size * 10, cudaMemcpyHostToDevice)) {
fprintf(stderr, "Failed to copy data to d_obj\n");
}
if (cudaSuccess != cudaMemcpy(d_obj2, obj2, size * 10, cudaMemcpyHostToDevice)) {
fprintf(stderr, "Failed to copy data to d_obj2\n");
}

kernel_testing << < GRID, BLOCK >> >(d_intersects, d_obj, d_obj2);


cudaError_t s = cudaMemcpy(intersects, d_intersects, sizeof(int) * 100, cudaMemcpyDeviceToHost);
fprintf(stderr, "Error is: %s", cudaGetErrorString(s));
cudaFree(d_intersects);
cudaFree(d_obj);
cudaFree(d_obj2);
return 0;
}

由于某种原因,代码总是在cudaMemcpyDeviceToHost处失败。 ,而且我看不出为什么应该这样做的原因。我尝试过使用不同的对象(三角形、球体等)启动,但当我需要将数据从设备复制回主机时,它总是失败。感谢任何帮助和/或建议,我对使用 CUDA 编程非常陌生。谢谢。

编辑:错误代码表示遇到了非法内存访问,但我不明白为什么会发生这种情况。

编辑2:所以我删除了所有双指针并“展平”我的数组,但我仍然遇到同样的问题。我现在完全没有想法了。

最佳答案

我想我曾经遇到过这样的问题,我的解决方案是:

cudaError_t status = cudaMemcpy(devPtr, srcPtr, size * sizeof(int), cudaMemcpyHostToDevice);
if (status == cudaSuccess) { ... }

尝试不要直接将函数与 cudaSuccess 进行比较,而是通过变量进行比较。

关于c++ - cudaMemcpyDeviceToHost() 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29978457/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com