How to dynamically allocate arrays inside a kernel?

后端 未结 5 1770
耶瑟儿~
耶瑟儿~ 2020-12-13 00:42

I need to dynamically allocate some arrays inside the kernel function. How can a I do that?

My code is something like that:

__global__ func(float *gr         


        
5条回答
  •  醉梦人生
    2020-12-13 01:23

    Dynamic memory allocation is only supported on compute capability 2.x and newer hardware. You can use either the C++ new keyword or malloc in the kernel, so your example could become:

    __global__ func(float *grid_d,int n, int nn){  
        int i,j;  
        float *x = new float[n], *y = new float[nn];   
    }
    

    This allocates memory on a local memory runtime heap which has the lifetime of the context, so make sure you free the memory after the kernel finishes running if your intention is not to use the memory again. You should also note that runtime heap memory cannot be accessed directly from the host APIs, so you cannot pass a pointer allocated inside a kernel as an argument to cudaMemcpy, for example.

提交回复
热议问题