【问题标题】:How do you read a multidimensional array out of clEnqueueReadBuffer?如何从 clEnqueueReadBuffer 中读取多维数组?
【发布时间】:2013-06-28 15:58:25
【问题描述】:

我有一个二维数组 C,我像这样实例化它:

const int wA = 16;
float * C[wA];
for(int i = 0; i < hA; i++)
{
C[i] = new float[hA];
for(int i2 = 0; i2 < hA; i2++)
    C[i][i2] = 0;
}

/* looks like this:
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
*/

我创建了一个在 C 上运行的内核:

__kernel void simpleMultiply(__global float* outputC, 
                            int widthA, 
                            int heightA, 
                            int widthB, 
                            int heightB, 
                            __global float * inputA, 
                            __global float * inputB)
{
    int row = get_global_id(1);
    int col = get_global_id(0);
    float sum = 0.0f;
    for(int i = 0; i < widthA; i++)
    {
        sum += inputA[row*widthA+i] * inputB[i*widthB+col];
    }
    outputC[row*widthB+col] = sum;
}

一切顺利。从设置上下文到创建缓冲区、创建内核、程序、clEnqueueNDRangeKernel、clEnqueueReadBuffer 等,我一直得到状态的 CL_SUCCESS。

但是当我去阅读输出时它崩溃了。

status = clEnqueueNDRangeKernel(cmdQueue, kernel, 2, NULL, globalws, localws, 0, NULL, NULL);
cout << "\nclEnqueueNDRangeKernel: " << (status == CL_SUCCESS ? "SUCCESS" : "FAIL"); // prints SUCCESS
status = clEnqueueReadBuffer(cmdQueue, bufferC, CL_TRUE, 0, wC*hC*sizeof(float), (void*)C, 0, NULL, NULL);
cout << "\nclEnqueueReadBuffer: " << (status == CL_SUCCESS ? "SUCCESS" : "FAIL"); // prints SUCCESS
cout << "\nC[0][0]: " << C[0][0]; // <--crash

我对 C++ 和 OpenCL 一样陌生,所以这可能是由于对 C++ 中的数组和指针理解不足。

整个代码是here

【问题讨论】:

  • 你确定第 67 行是阻塞读取吗?也许您在第 69 行读完之前正在计算。另外,您的 C 是指针数组,因此可能不知道每个元素的维度?可以试试纯二维数组和纯双指针吗?
  • 第 67 行的第三个参数表示使其阻塞。所以它肯定会阻塞。我需要一天左右的时间才能有时间重做数组(我是 C++ 新手)。

标签: opencl


【解决方案1】:

数组

float * C[wA];

float * 指针的一维数组。因此,您还没有在内存中创建具有连续行和列的二维数组。但是您已经创建了一个指向行的指针数组。

所以你应该在主机数组 C 上展平并像在内核上一样索引它。

float * C;

c = new float[ha * ha]; // Create a  contiguous memory area  to be addressed  in a 2D pattern

memset( C, 0, ha * ha  * sizeof(float) ); // Set all bytes to zero


...

现在您可以在运行内核后寻址 C 数组

cout << C[ icolumn  + irow * ha ];  // icolumn and irow are your row and columns indices  

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-12
    相关资源
    最近更新 更多