c++ - CUDA 在设备上静态分配数据

标签 c++ cuda parallel-processing nvcc

我一直在尝试分配一个可以被每个内核函数访问的变量。 我的尝试是下面附加的代码,但它不会编译,因为内核无法查看 dArray 访问。在 C++ 中,您可以将变量放在顶部或声明 static 以在整个程序的每个范围内访问。

__global__ void StoreThreadNumber()
{
    dArray[threadIdx.x] = threadIdx.x;
}

int main( int argc, char** argv)
{
    unsigned __int8 Array[16] = { 0 };
    unsigned __int8 dArray[16];

    for( __int8 Position = 0; Position < 16; Position++)
        cout << Array[Position] << " ";
    cout << endl;

    cudaMalloc((void**) dArray, 16*sizeof(__int8));
    cudaMemcpy( dArray, Array, 16*sizeof(__int8), cudaMemcpyHostToDevice);

    StoreThreadNumber<<<1, 16>>>();

    cudaMemcpy( Array, dArray, 16*sizeof(__int8), cudaMemcpyDeviceToHost);

    for( __int8 Position = 0; Position < 16; Position++)
        cout << Array[Position] << " ";
    cout << endl;

    cudaFree(dArray);
}

最佳答案

您可以在 CUDA 中拥有 __device____constant__ 类型的全局变量。因此,例如,如果您使用 cudaMemcpyToSymbol()__constant__ 指针变量初始化为设备指针的地址,则您可以通过 __constant__ 访问该指针 变量:

__constant__ int* dArrayPtr;

__global__ void StoreThreadNumber()
{
    dArrayPtr[threadIdx.x] = threadIdx.x;
}

只需确保在运行内核之前从主机代码正确初始化 dArrayPtr。

关于c++ - CUDA 在设备上静态分配数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5963305/

相关文章:

c - 全有或全无 - 快速启发式最短路径算法(并行?)

c++ - 多线程 std::filesystem::exists 调用有意义吗?

c++ - 错误/usr/include/string.h :652:42: error: ‘memcpy’ was not declared in this scope while building caffe

python - 如何提高 python 循环速度?

c++ - CUDA - 设备上的推力::排序仅返回 0

c++ - 如何提高内存使用性能?

java - 为什么不能并行减少流流?/流已经被操作或关闭

c++ - Kamada-Kawai 布局的停止条件

c++ - 如何使用线性渐变创建文本?

c++ - CLion,MinGW和SDL2:进程结束,退出代码为-1073741515(0xC0000135)