cuda 中自定义结构的内存分配

问题描述 投票:0回答:1

我有这些结构:

typedef struct Edge {
    int start;
    int end;
} Edge;

typedef struct {
    int deg;
    int nome;
    Edge *edges;
} Vertex;

在我的主函数中,我有一个初始结构

Vertex* initial_partition
,其中包含图形的所有顶点,并且所有字段都已正确填充。
现在我想构建一个与这个一模一样的设备结构,所以我这样做了:

Vertex* d_initial_partition;
cudaMalloc((void **)&d_initial_partition, numNodes * sizeof(Vertex));
cudaMemcpy(d_initial_partition, initial_partition, numNodes * sizeof(Vertex), cudaMemcpyHostToDevice);

但我注意到这个操作并没有复制结构体的字段

Edge*
。我什至尝试过像这样单独分配边缘:

for (int i = 0; i < numNodes; ++i) {
        cudaMalloc((void**)&d_initial_partition[i].edges, sizeof(Edge*));
    if(initial_partition[0].deg != 0){
            cudaMemcpy(d_initial_partition[i].edges, initial_partition[i].edges, initial_partition[i].deg * sizeof(Edge), cudaMemcpyHostToDevice);
    }
}

甚至像这样:

Vertex* d_initial_partition;
cudaMalloc((void **)&d_initial_partition, numNodes * sizeof(Vertex));
for(int i = 0; i < numNodes; i++){
    cudaMalloc((void**)&d_initial_partition[i].edges, initial_partition[i].deg * sizeof(Edge));
    cudaMemcpy(&d_initial_partition[i].edges, &initial_partition[i].edges, sizeof(Edge), cudaMemcpyHostToDevice);
    cudaMemcpy(&d_initial_partition[i], &initial_partition[i], sizeof(Vertex), cudaMemcpyHostToDevice);
}

但什么也没有。有人可以让我看看如何保存

d_initial_partition
向量中的所有信息吗?

struct parallel-processing cuda
1个回答
0
投票

看来你必须

  1. 在设备上分配
    Vertex
    数组。
  2. 为设备上的
    Edge
    成员分配
    edges
    数组。
  3. 将指向
    Edge
    数组的指针设置为每个
    edges
    成员。请注意,
    edges
    成员位于设备上。
Vertex* d_initial_partition;
// 1
cudaMalloc((void **)&d_initial_partition, numNodes * sizeof(Vertex));
// copy deg and nome
cudaMemcpy(d_initial_partition, initial_partition, numNodes * sizeof(Vertex), cudaMemcpyHostToDevice);
for (int i = 0; i < numNodes; i++) {
    Edge* edges;
    // 2
    cudaMalloc((void **)&edges, initial_partition[i].deg * sizeof(Edge));
    // copy edges
    if(initial_partition[0].deg != 0){
        cudaMemcpy(edges, initial_partition[i].edges, initial_partition[i].deg * sizeof(Edge), cudaMemcpyHostToDevice);
    }
    // 3
    cudaMemcpy(&d_initial_partition[i].edges, &edges, sizeof(Edge*), cudaMemcpyHostToDevice);
}
© www.soinside.com 2019 - 2024. All rights reserved.