Dynamic global memory allocation in opencl kernel

坚强是说给别人听的谎言 提交于 2019-12-06 13:15:17

问题


Is it possible to dynamically allocate global memory from the kernel? In CUDA it is possible but I would like to know if this is also possible in OpenCL on Intel GPUs.

for example:

__kernel void foo()

{

,
,
,

call malloc or clCreateBuffer here


} 

is it possible? If yes how exactly?


回答1:


No, this is not currently allowed in OpenCL.

You could implement your own heap by creating one very large buffer up front, and then 'allocate' regions of the buffer by handing out offsets (using atomic_add to avoid synchronisation issues). However, in most cases I suspect it would be better just to rethink your algorithm and come up with an approach that doesn't require dynamic memory allocation in the first place.


Here's an example that uses a preallocated buffer to emulate dynamic heap allocation inside kernels. The heap and index of the next free element are passed into the kernel as arguments, and need to passed onto our malloc function. In OpenCL 2.0, we could use program scope global variables to avoid the need to do this.

global void* malloc(size_t size, global uchar *heap, global uint *next)
{
  uint index = atomic_add(next, size);
  return heap+index;
}

kernel void foo(global uchar *heap, global uint *next)
{
  // Allocate some memory from heap
  global void *data = malloc(4, heap, next);
  ...
}


来源:https://stackoverflow.com/questions/25445189/dynamic-global-memory-allocation-in-opencl-kernel

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!