我開始學習CUDA,並且我想寫一個簡單的程序,將一些數據複製到GPU,對其進行修改並將其傳回。我已經搜索並試圖找到我的錯誤。我很確定這個問題出現在我的內核中,但我並不完全確定哪裏出了問題。CUDA:二維數組索引給出意想不到的結果
這裏是我的內核:
__global__ void doStuff(float* data, float* result)
{
if (threadIdx.x < 9) // take the first 9 threads
{
int index = threadIdx.x;
result[index] = (float) index;
}
}
這裏是我main
相關部分:
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
/*
Setup
*/
float simple[] = {-1.0, -2.0, -3.0, -4.0, -5.0, -6.0, -7.0, -8.0, -9.0};
float* data_array;
float* result_array;
size_t data_array_pitch, result_array_pitch;
int width_in_bytes = 3 * sizeof(float);
int height = 3;
/*
Initialize GPU arrays
*/
cudaMallocPitch(&data_array, &data_array_pitch, width_in_bytes, height);
cudaMallocPitch(&result_array, &result_array_pitch, width_in_bytes, height);
/*
Copy data to GPU
*/
cudaMemcpy2D(data_array, data_array_pitch, simple, width_in_bytes, width_in_bytes, height, cudaMemcpyHostToDevice);
dim3 threads_per_block(16, 16);
dim3 num_blocks(1,1);
/*
Do stuff
*/
doStuff<<<num_blocks, threads_per_blocks>>>(data_array, result_array);
/*
Get the results
*/
cudaMemcpy2D(simple, width_in_bytes, result_array, result_array_pitch, width_in_bytes, height, cudaMemcpyDeviceToHost);
for (int i = 1; i <= 9; ++i)
{
printf("%f ", simple[i-1]);
if(!(i%3))
printf("\n");
}
return 0;
}
當我運行此我得到0.000000 1.000000 2.00000
用於第一列和垃圾其他兩個。
如果你這樣做[CUDA錯誤檢查( http://stackoverflow.com/questions/14038589/what-is-the-canonical-way-to-check-for-errors-using-the-cuda-runtime-api)關於所有cuda API調用和內核調用,請執行你有任何錯誤?當你用'cuda-memcheck'運行你的代碼時會發生什麼? –
一切都返回'cudaSuccess'。 – al92
訪問數組中的元素時,我是否需要考慮音高?我現在在看NVIDIA的指南第30頁。 – al92