簡體   English   中英

Cuda 你如何使用帶有 __constant__ 的指針數組

[英]Cuda how do you use a pointer array with __constant__

我需要動態調整在內核實例的每個線程中查詢的 int* 指針數組的大小。

我的目標是制作一個 int 數組,其中直到運行時我才知道數組的大小(因此它不能是固定大小)。

當我這樣做時:

#include "CudaTest.cuh"
#include <stdio.h>
#include <iostream>
#include <ctime>

using namespace std;

__constant__ int* deviceArray;

bool CHECK(cudaError_t type)
{
    bool flag = true;
    const cudaError_t error = type;
    if (error != cudaSuccess)
    {
        printf("\n\n Error: %s:%d, ", __FILE__, __LINE__);
        printf("\n\n code:%d, reason: %s\n", error, cudaGetErrorString(error));
        flag = false;
    }
    return flag;
}

__global__
void myKernel()
{


    //=> // constValue should be 57. But getting an Invalid memory access error here. 
    int constValue = deviceArray[7];
    printf("\n deviceArray[7]; is: %i \n", constValue);

}


int main()
{
    int* hostAry = new int[8]();

    hostAry[7] = 57;
    CHECK(cudaMemcpyToSymbol(deviceArray, hostAry, sizeof(hostAry), 0, cudaMemcpyHostToDevice));

    myKernel << < 1, 1 >> > ();
    CHECK(cudaDeviceSynchronize());
    return 0;
}

我收到此錯誤:錯誤:

代碼:700,原因:遇到非法內存訪問

主機陣列的內存不會復制到 deviceArray。 我把頭撞在牆上,這通常意味着我從根本上不理解某些東西。

你如何使用帶有__constant__的指針數組

你沒有。 這不可能。

常量內存必須在編譯時靜態定義。 這意味着如果您想要一個常量內存數組,則必須在編譯代碼時定義大小。 沒有辦法動態分配常量內存。

唯一現實的解決方案是將__constant__數組定義為最大大小,然后定義第二個__constant__變量,指示用於給定內核調用的數組大小。 所以像:

__constant__ int devicearray[MAXSIZE];
__constant__ int devicearray_n;

在啟動內核之前,將您需要的數據復制到devicearray並將元素數量復制到devicearray_n

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM