我目前正在浏览http://code.google.com/p/stanford-cs193g-sp2010/上的教程示例以学习CUDA.__global__下面给出了演示功能的代码.它只创建了两个阵列,一个在CPU上,一个在GPU上,用7号填充GPU阵列,并将GPU阵列数据复制到CPU阵列中.
#include <stdlib.h>
#include <stdio.h>
__global__ void kernel(int *array)
{
int index = blockIdx.x * blockDim.x + threadIdx.x;
array[index] = 7;
}
int main(void)
{
int num_elements = 256;
int num_bytes = num_elements * sizeof(int);
// pointers to host & device arrays
int *device_array = 0;
int *host_array = 0;
// malloc a host array
host_array = (int*)malloc(num_bytes);
// cudaMalloc a device array
cudaMalloc((void**)&device_array, num_bytes);
int block_size = 128;
int grid_size = num_elements / block_size;
kernel<<<grid_size,block_size>>>(device_array); …Run Code Online (Sandbox Code Playgroud) 该cudaMalloc()函数使用以下定义:
cudaMalloc (
void ** devPtr,
size_t size)
Run Code Online (Sandbox Code Playgroud)
这里和这里的响应很好地解释了为什么应该定义函数来接受指向指针的指针.
但是,我不太清楚为什么我们需要在调用函数类型为void**时输入我们提供的参数.例如,在函数调用中:
catch_status = cudaMalloc((void**)&device_array, num_bytes);
Run Code Online (Sandbox Code Playgroud)
呈现在这里.
据我了解,定义一个接受void类型的函数可以提供更大的灵活性.即看看cudaMalloc()函数的定义,我将其解释为它可以接受指向任何类型对象的指针.因此,为什么&device_array在调用函数时需要输入强制转换(在上面的例子中).(这种类型转换的语法在cudaMalloc()我在整个网络中看到的例子中似乎非常普遍).只要&device_array满足它是"指向任何类型数据的指针"的条件,就不足以(a)满足参数cudaMalloc()接受的函数定义和(b)完成我们的编程目标吗?
我在这里错过了什么?
我是一个CUDA新手,所以想知道是否有人可以帮助我.
我读到pinning可以严重改善你的程序性能,所以我试着这样做.我在GeForce GT 330上运行我的代码,它的计算能力为1.0.
当我运行我的程序时,我得到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_ */
Run Code Online (Sandbox Code Playgroud)
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, …Run Code Online (Sandbox Code Playgroud) 我正在尝试在随附的代码中启动内核。我收到消息“内核启动失败:参数无效”。
// System includes
#include <stdio.h>
#include <assert.h>
// CUDA runtime
#include <cuda_runtime.h>
// Helper functions and utilities to work with CUDA
#include <helper_functions.h>
// This will output the proper CUDA error strings in the event that a CUDA host call returns an error
#define checkCudaErrors(err) __checkCudaErrors (err, __FILE__, __LINE__)
inline void __checkCudaErrors(cudaError err, const char *file, const int line )
{
if(cudaSuccess != err)
{
fprintf(stderr, "%s(%i) : CUDA Runtime API error %d: %s.\n",file, line, (int)err, cudaGetErrorString( err ) …Run Code Online (Sandbox Code Playgroud)