为什么我的内核动态内存分配对于较大的网格大小会失败?

Why do my in-kernel dynamic memory allocations fail for larger grid sizes?

我需要在内核函数中动态分配一些数组。这是代码:

__global__
void kernel3(int N)
{
    int index = blockIdx.x*blockDim.x + threadIdx.x;
    if (index < N)
    {
        float * cost = new float[100];
        for (int i = 0; i < 100; i++)
            cost[i] = 1;
    }
}

int main()
{
    cudaDeviceSynchronize();
    cudaThreadSynchronize();
    size_t mem_tot_01 = 0;
    size_t mem_free_01 = 0;
    cudaMemGetInfo(&mem_free_01, &mem_tot_01);
    cout << "Free memory " << mem_free_01 << endl;
    cout << "Total memory " << mem_tot_01 << endl;
    system("pause");
    int blocksize = 256;
    int aaa = 16000;
    int numBlocks = (aaa + blocksize - 1) / blocksize;
    kernel3 << <numBlocks, blocksize >> >(aaa);
    cudaDeviceSynchronize();
    cudaError_t err1 = cudaGetLastError();
    if (err1 != cudaSuccess)
    {
        printf("Error: %s\n", cudaGetErrorString(err1));
        system("pause");

    }


    cudaMemGetInfo(&mem_free_01, &mem_tot_01);
    cout << "Free memory " << mem_free_01 << endl;
    cout << "Total memory " << mem_tot_01 << endl;
    system("pause");
}

第一轮cudaMemGetInfo: 免费 memory:3600826368 总计 memory:4294967297

我收到一个错误: Error:unspecified启动失败

并且我尝试将 "int aaa" 更改为某个较小的值,它不会出错,但内存信息不等于我分配的值。 它出什么问题了?内存要够用,16000x100x32=512x10e5<3600826368

new运算符分配的设备内存来自固定大小的运行时堆。

如果您的代码需要大量运行时堆内存,您可能需要在 运行 任何内核之前增加堆的大小。 NVIDIA为此提供了cudaDeviceSetLimit API,它与cudaLimitMallocHeapSize标志一起使用来设置堆的大小。