我对CUDA很陌生,而且我正在尝试创建一件事我遇到了很多问题。问题如下:我有一个方形矩阵(现在它是5x5但它会更大,比如1k x 1k),这个矩阵用随机数填充然后我将这个矩阵传递给设备,它会做一些工作(现在只应用一些阈值)。代码如下:
#define N 3
#define MINTHRESHOLD 100
#define MAXTHRESHOLD 200
#define THREADS 128
__global__ void applyThresh(int *d_base, int *d_thresh) {
int tid = blockDim.x * blockIdx.x + threadIdx.x;
int stride = blockDim.x * gridDim.x;
while(tid < N) {
if(d_base[tid] > MAXTHRESHOLD) {
d_thresh[tid] = MAXTHRESHOLD;
} else if(d_base[tid] < MINTHRESHOLD) {
d_thresh[tid] = MINTHRESHOLD;
} else {
d_thresh[tid] = d_base[tid];
}
tid += stride;
}
}
int main( void ) {
cudaError_t err;
int *base, *thresh, *d_base, *d_thresh, i;
base = (int*)malloc((N * N) * sizeof(int));
thresh = (int*)malloc((N * N) * sizeof(int));
err = cudaMalloc((void**)&d_base, (N * N) * sizeof(int));
if(err != cudaSuccess) {printf("ERROR 1"); return -1;}
err = cudaMalloc((void**)&d_thresh, (N * N) * sizeof(int));
if(err != cudaSuccess) {printf("ERROR 2"); return -1;}
for(i = 0; i < N * N; i++) {
base[i] = rand() % 256;
thresh[i] = 0;
}
err = cudaMemcpy(d_base, base, (N * N) * sizeof(int), cudaMemcpyHostToDevice);
if(err != cudaSuccess){printf("ERROR 3"); return -1;}
applyThresh<<<(N + THREADS - 1)/THREADS , THREADS>>>(d_base, d_thresh);
err = cudaMemcpy(thresh, d_thresh, (N * N) * sizeof(int), cudaMemcpyDeviceToHost);
if(err != cudaSuccess) {printf("ERROR 4"); return -1;}
for(i = 0; i < N *N; i++) {
printf("%d -> ", base[i]);
printf("%d\n", thresh[i]);
}
free(base);
free(thresh);
cudaFree(d_base);
cudaFree(d_thresh);
return 0;
}
该计划的输出如下:
41 -> 100
35 -> 100
190 -> 190
132 -> 132
225 -> 200
108 -> -1082130432
214 -> -1082130432
174 -> 1007746492
82 -> 100509168
我真的无法理解这个问题...我认为它可能是由我用来访问矩阵的索引引起的,但我真的找不到解决方案:(
答案 0 :(得分:2)
在你的内核中,使用
行while(tid < N) {
您只处理数组的第一个N
元素。将其更改为N * N
。