我试图在代码中使用常量内存,并从内核分配常量内存值,而不是使用 cudacopytosymbol。
#include <iostream>
using namespace std;
#define N 10
//__constant__ int constBuf_d[N];
__constant__ int *constBuf;
__global__ void foo( int *results )
{
int tdx = threadIdx.x;
int idx = blockIdx.x * blockDim.x + tdx;
if( idx < N )
{
constBuf[idx]=1;
results[idx] = constBuf[idx];
}
}
// main routine that executes on the host
int main(int argc, char* argv[])
{
int *results_h = new int[N];
int *results_d;
cudaMalloc((void **)&results_d, N*sizeof(int));
foo <<< 1, 10 >>> ( results_d );
cudaMemcpy(results_h, results_d, N*sizeof(int), cudaMemcpyDeviceToHost);
for( int i=0; i < N; ++i )
printf("%i ", results_h[i] );
delete(results_h);
}
输出显示
6231808 6226116 0 0 0 0 0 0 0 0
我希望程序在代码中打印通过内核分配给常量内存的值。
顾名思义,常量内存对于设备代码来说是常量/只读的。您尝试做的事情是非法的,无法实现。
要在常量内存中设置值,当前有两种选择:
- 通过主机代码设置值
cudaMemcpyToSymbol
API 调用(或其等效项)
- 在编译时使用静态初始化
在后一种情况下,类似这样的事情会起作用:
__constant__ int constBuf[N] = { 16, 2, 77, 40, 12, 3, 5, 3, 6, 6 };
__global__ void foo( int *results )
{
int tdx = threadIdx.x;
int idx = blockIdx.x * blockDim.x + tdx;
if( tdx < N )
{
results[idx] = constBuf[tdx]; // Note changes here!
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)