我到处都浏览过这个站点和其他站点,但没有任何效果。我要针对我的具体情况提出问题。
我有一堆矩阵,目标是使用内核让GPU在所有矩阵上执行相同的操作。我很确定我可以使内核正常工作,但不能使cudaMalloc / cudaMemcpy工作。
我有一个指向Matrix结构的指针,该结构具有一个称为元素的成员,该成员指向一些浮点数。我可以做所有的非cuda malloc。
感谢您提供的所有/所有帮助。
代码:
typedef struct {
int width;
int height;
float* elements;
} Matrix;
int main void() {
int rows, cols, numMat = 2; // These are actually determined at run-time
Matrix* data = (Matrix*)malloc(numMat * sizeof(Matrix));
// ... Successfully read from file into "data" ...
Matrix* d_data;
cudaMalloc(&d_data, numMat*sizeof(Matrix));
for (int i=0; i<numMat; i++){
// The next line doesn't work
cudaMalloc(&(d_data[i].elements), rows*cols*sizeof(float));
// Don't know if this works
cudaMemcpy(d_data[i].elements, data[i].elements, rows*cols*sizeof(float)), cudaMemcpyHostToDevice);
}
// ... Do other things ...
}
谢谢!
您必须知道内存所在的位置。malloc分配主机内存,cudaMalloc分配设备上的内存并返回指向该内存的指针。但是,此指针仅在设备功能中有效。
您想要的可以实现如下:
typedef struct {
int width;
int height;
float* elements;
} Matrix;
int main void() {
int rows, cols, numMat = 2; // These are actually determined at run-time
Matrix* data = (Matrix*)malloc(numMat * sizeof(Matrix));
// ... Successfully read from file into "data" ...
Matrix* h_data = (Matrix*)malloc(numMat * sizeof(Matrix));
memcpy(h_data, data, numMat * sizeof(Matrix);
for (int i=0; i<numMat; i++){
cudaMalloc(&(h_data[i].elements), rows*cols*sizeof(float));
cudaMemcpy(h_data[i].elements, data[i].elements, rows*cols*sizeof(float)), cudaMemcpyHostToDevice);
}// matrix data is now on the gpu, now copy the "meta" data to gpu
Matrix* d_data;
cudaMalloc(&d_data, numMat*sizeof(Matrix));
cudaMemcpy(d_data, h_data, numMat*sizeof(Matrix));
// ... Do other things ...
}
弄清楚点:Matrix* data
包含主机上的数据。Matrix* h_data
在元素中包含一个指向设备内存的指针,这些元素可以作为参数传递给内核。内存在GPU上。Matrix* d_data
在GPU上完全可用,并且可以像主机上的数据一样使用。
在您的内核代码中,您现在要访问矩阵值,例如,
__global__ void doThings(Matrix* matrices)
{
matrices[i].elements[0] = 42;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句