0

我正在尝试深入研究openCL。目前我在问自己为什么在传输到 GPU 时标量与数组不同。

下面有两个输入。一个标量和一个数组。为什么将它们传输到 GPU 会有如此大的差异?

提前致谢!

// input size
int input_size = 4;
err = clSetKernelArg(kernel, 0, sizeof(unsigned int), &_input_size);
if (err != CL_SUCCESS) {
  throw std::runtime_error("Failed to set kernel arguments!");
}

// input
int input[input_size];
input[0] = 1;
input[1] = 2;
input[2] = 3;
input[3] = 4;
cl_mem cl_input = clCreateBuffer(context,  CL_MEM_READ_ONLY, sizeof(int) * _input_size, NULL, NULL);
if (!cl_input) {
  throw std::runtime_error("Failed to allocate device memory!");
}
err  = clSetKernelArg(kernel, 1, sizeof(cl_mem), &cl_input);
if (err != CL_SUCCESS) {
  throw std::runtime_error("Failed to set kernel arguments!");
}
err = clEnqueueWriteBuffer(commands, cl_input, CL_TRUE, 0, sizeof(int) * _input_size, _input, 0, NULL, NULL);
if (err != CL_SUCCESS) {
  throw std::runtime_error("Failed to write to source array!");
}

// output
int output_size = 4;
int output[output_size];
cl_mem cl_output = clCreateBuffer(context, CL_MEM_WRITE_ONLY, sizeof(int) * _output_size, NULL, NULL);
if (!cl_output) {
  throw std::runtime_error("Failed to allocate device memory!");
}
err = clSetKernelArg(kernel, 2, sizeof(cl_mem), &cl_output);
if (err != CL_SUCCESS) {
  throw std::runtime_error("Failed to set kernel arguments!" );
}
4

1 回答 1

2

在 OpenCL 中,标量是按值传递的,并且是每个线程的常量。数组通过引用(地址)传递,可以用作输入(只读)、输出(只写)或输入/输出(读/写)。数组需要 cl_mem 对象作为参数传递。cl_mem 是描述数组的元对象。标量非常简单,它们只需要它们的大小作为元数据。

所以在你上面的例子中,内核应该看起来像....

kernel void mykernel( const int arg0,  global int * arg1, global int * arg2 ... ) {
    int  i =  get_global_id(0);

    // In every thread arg0  is constant value and cannot be changed

    if (i < arg0)
        arg2[i] = arg[1[i];
}
于 2013-01-19T03:45:43.437 回答