【问题标题】:cudaMallocHost is failing to allocate even the smallest of memorycudaMallocHost 甚至无法分配最小的内存
【发布时间】:2013-03-02 23:55:37
【问题描述】:

我是一个 CUDA 新手,所以想知道是否有人可以帮助我。

我读到固定可以极大地提高您的程序性能,因此我正在努力做到这一点。我在计算能力为 1.0 的 GeForce GT 330 上运行我的代码。

当我运行我的程序时,我发现 cudaMallocHost 无法分配内存,因此我将我的问题浓缩为一个小示例,如下所示。

Mesh.hpp

#ifndef MESH_HPP_

#define MESH_HPP_


#include <cstddef>
#include <vector>

#include <driver_types.h>

class Mesh{
public:
  Mesh();
  ~Mesh();  
  void pin_data();

  std::vector<size_t> _a;
  size_t* _a_pinned;

private:
  void cuda_check(cudaError_t success);
};

#endif /* MESH_HPP_ */

Mesh.cpp

#include <iostream>
#include <cmath>
#include <vector>
#include <string.h>

#include <cuda.h>
#include <cuda_runtime.h>

#include "Mesh.hpp"

Mesh::Mesh(){
  for(size_t i = 0; i < 10; i++){
    _a.push_back(i);
  }
}

Mesh::~Mesh() {
  cudaFreeHost(_a_pinned);
}

void Mesh::pin_data() {
  size_t _a_bytes = sizeof(size_t) * _a.size();

  cuda_check(cudaMallocHost((void **)_a_pinned, _a_bytes));
  memcpy(_a_pinned, &_a[0], _a_bytes);
}

void Mesh::cuda_check(cudaError_t status) {
  if (status != cudaSuccess) {
    std::cout << "Error could not allocate memory result " << status << std::endl;
    exit(1);
  }
}

Main.cpp

#include <cstdlib>
#include <iostream>

#include "Mesh.hpp"


int main(int argc, char **argv){

  Mesh *mesh = new Mesh();
  mesh->pin_data();

  delete mesh;

  return EXIT_SUCCESS;
}

当我运行我的代码时,输​​出是:

'错误无法分配内存结果11'

【问题讨论】:

    标签: c++ cuda


    【解决方案1】:

    改变这一行:

    cuda_check(cudaMallocHost((void **)_a_pinned, _a_bytes));
    

    到这里:

    cuda_check(cudaMallocHost((void **)&_a_pinned, _a_bytes));
    

    (唯一的改变是添加和号)

    cudaMalloc 操作期望修改指针值,因此它们must be passed the address of the pointer to modify,而不是指针本身。

    这为我解决了问题。我仍然对&lt;size_t&gt; 的向量感到有些困惑,但对于每个人来说都是如此。

    如果您愿意,作为建议,在您的 Mesh:cuda_check 方法中,您可以像这样添加一行:

      std::cout << "Error could not allocate memory result " << status << std::endl;
      std::cout << "Error is: " << cudaGetErrorString(status) << std::endl; //add this line
    

    【讨论】:

    • 是的,解决了,谢谢!我最初得到了带有 size_t 向量的代码,所以没有改变它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多