【问题标题】:Passing a Struct Containing a Vector to a CUDA Kernel将包含向量的结构传递给 CUDA 内核
【发布时间】:2018-06-02 04:09:07
【问题描述】:

我有一个大代码,我需要将一个结构传递给一个 CUDA 内核,该内核具有大量用于参数和向量的整数。我不知道如何将结构传递给 CUDA 内核。我已将其复制到设备上,但尝试编译时出现以下错误:

test_gpu.cpp:63:17: error: invalid operands to binary expression ('void (*)(Test)' and 'dim3')
    computeTotal<<dimGrid, dimBlock>>(test_Device);
test_gpu.cpp:63:36: error: invalid operands to binary expression ('dim3' and 'Test *')
    computeTotal<<dimGrid, dimBlock>>(test_Device);

附件是一个几乎可以工作的小代码示例,有什么想法吗?

#include <stdio.h>
#include <stdlib.h>
#include <cuda_runtime_api.h>
#include <cuda.h>
#include <cuda_runtime.h>
#include <device_functions.h>
#include <device_launch_parameters.h>
#include <vector>
#include <string>

typedef struct Test{
    int x;
    int y;
    int z;
    std::vector<int> vector;
    std::string string;
}Test;

Test test;

__device__ void addvector(Test test, int i){
    test.x += test.vector[i];
    test.y += test.vector[i+1];
    test.z += test.vector[i+2];
}

__global__ void computeTotal(Test test){
    for (int tID = threadIdx.x; tID < threadIdx.x; ++tID )
    addvector(test, tID);
}

int main()
{
    Test test_Host;
    int vector_size = 512;
    test_Host.x = test_Host.y = test_Host.z = 0;
    for (int i=0; i < vector_size; ++i)
    {
        test_Host.vector.push_back(rand());
    }

    Test* test_Device;
    int size = sizeof(test_Host);
    cudaMalloc((void**)&test_Device, size);
    cudaMemcpy(test_Device, &test_Host, size, cudaMemcpyHostToDevice);

    dim3 dimBlock(16);

    dim3 dimGrid(1);

    computeTotal<<dimGrid, dimBlock>>(test_Device);


    return 0;
}

【问题讨论】:

  • std::vector 不能在设备代码中使用。您是否在.cpp 文件中编译此代码? CUDA 设备代码通常属于.cu 文件。
  • 是的,这是一个大型 C++ 代码,在 CPU 上使用 OpenMP 和 MPI。我在想我可能不得不从结构中取出向量并将其作为指针单独传递。

标签: c struct cuda


【解决方案1】:

C++ 标准库中的项目通常/通常不能在 CUDA 设备代码中使用。对此的文档支持是 here

对于这种特殊情况,这意味着您可能遇到std::vectorstd::string 的问题。一种可能的解决方法是用普通的 C 样式数组替换它们:

#define MAX_VEC_SIZE 512
#define MAX_STR_SIZE 512

typedef struct Test{
    int x;
    int y;
    int z;
    int vec[MAX_VEC_SIZE];
    char str[MAX_STR_SIZE];
}Test;

这当然需要在代码的其他地方进行更改。

【讨论】:

  • ... 并考虑将这些数组固定,即使用 cudaMallocHost() 分配。
猜你喜欢
  • 2011-05-09
  • 2015-08-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-14
  • 2021-06-10
  • 1970-01-01
相关资源
最近更新 更多