我在这里提供了一个教程:http://opencl.codeplex.com/wikipage?title=OpenCL%20Tutorials%20-%201
他们列出的内核是这样的,它计算两个数字的和并将其存储在输出变量中:
__kernel void vector_add_gpu (__global const float* src_a,
__global const float* src_b,
__global float* res,
const int num)
{
/* get_global_id(0) returns the ID of the thread in execution.
As many threads are launched at the same time, executing the same kernel,
each one will receive a different ID, and consequently perform a different computation.*/
const int idx = get_global_id(0);
/* Now each work-item asks itself: "is my ID inside the vector's range?"
If the answer is YES, the work-item performs the corresponding computation*/
if (idx < num)
res[idx] = src_a[idx] + src_b[idx];
}1)例如,假设执行的运算比求和复杂得多--这是它自己的功能。让我们称它为ComplexOp(in1,in2,out)。我该如何实现这个函数,以便vector_add_gpu()可以调用和使用它?你能给出示例代码吗?
2)现在让我们把这个例子发挥到极致,现在我想调用一个对这两个数字进行操作的泛型函数。我如何设置它,以便内核可以传递一个指向此函数的指针,并在必要时调用它?
发布于 2011-08-26 09:29:24
是的,这是可能的。您只需记住,OpenCL是基于C99的,但有一些注意事项。您可以在同一个内核文件中创建其他函数,也可以在单独的文件中创建其他函数,只需将其包含在开头即可。辅助函数不需要声明为内联,但是请记住,OpenCL将在调用时内联这些函数。在调用辅助函数时,指针也不可用。
示例
float4 hit(float4 ray_p0, float4 ray_p1, float4 tri_v1, float4 tri_v2, float4 tri_v3)
{
//logic to detect if the ray intersects a triangle
}
__kernel void detection(__global float4* trilist, float4 ray_p0, float4 ray_p1)
{
int gid = get_global_id(0);
float4 hitlocation = hit(ray_p0, ray_p1, trilist[3*gid], trilist[3*gid+1], trilist[3*gid+2]);
}发布于 2011-08-26 04:11:40
您可以在内核中使用辅助函数,请参阅OpenCL user defined inline functions。您不能将函数指针传递到内核。
https://stackoverflow.com/questions/7196552
复制相似问题