我目前正致力於使用僅使用1個線程的端口TERCOM algorithm來使用多線程。簡而言之,TERCOM算法接收5個測量值和航向,並將這些測量結果與預先存儲的地圖進行比較。該算法將選擇最佳匹配,即最低平均絕對差(MAD),並返回該位置。TERCOM算法 - 在CUDA中從單線程切換到多線程
該代碼完美工作與一個線程和for循環,但是當我嘗試使用多個線程和塊它返回錯誤的答案。看起來多線程版本不像「單線程」版本那樣「運行」計算。有誰知道我做錯了什麼?
下面是使用for循環的代碼
__global__ void kernel (int m, int n, int h, int N, float *f, float heading, float *measurements)
{
//Without threads
float pos[2]={0};
float theta=heading*(PI/180);
float MAD=0;
// Calculate how much to move in x and y direction
float offset_x = h*cos(theta);
float offset_y = -h*sin(theta);
float min=100000; //Some High value
//Calculate Mean Absolute Difference
for(float row=0;row<m;row++)
{
for(float col=0;col<n;col++)
{
for(float g=0; g<N; g++)
{
f[(int)g] = tex2D (tex, col+(g-2)*offset_x+0.5f, row+(g-2)*offset_y+0.5f);
MAD += abs(measurements[(int)g]-f[(int)g]);
}
if(MAD<min)
{
min=MAD;
pos[0]=col;
pos[1]=row;
}
MAD=0; //Reset MAD
}
}
f[0]=min;
f[1]=pos[0];
f[2]=pos[1];
}
這是我嘗試使用多線程
__global__ void kernel (int m, int n, int h, int N, float *f, float heading, float *measurements)
{
// With threads
int idx = blockIdx.x * blockDim.x + threadIdx.x;
int idy = blockIdx.y * blockDim.y + threadIdx.y;
float pos[2]={0};
float theta=heading*(PI/180);
float MAD=0;
// Calculate how much to move in x and y direction
float offset_x = h*cos(theta);
float offset_y = -h*sin(theta);
float min=100000; //Some High value
if(idx < n && idy < m)
{
for(float g=0; g<N; g++)
{
f[(int)g] = tex2D (tex, idx+(g-2)*offset_x+0.5f, idy+(g-2)*offset_y+0.5f);
MAD += abs(measurements[(int)g]-f[(int)g]);
}
if(MAD<min)
{
min=MAD;
pos[0]=idx;
pos[1]=idy;
}
MAD=0; //Reset MAD
}
f[0]=min;
f[1]=pos[0];
f[2]=pos[1];
}
到這裏進入內核
dim3 dimBlock(16,16);
dim3 dimGrid;
dimGrid.x = (n + dimBlock.x - 1)/dimBlock.x;
dimGrid.y = (m + dimBlock.y - 1)/dimBlock.y;
kernel <<< dimGrid,dimBlock >>> (m, n, h, N, dev_results, heading, dev_measurements);
MAD在這兩個代碼片段中都未初始化 – talonmies
初始化了MAD和pos,但沒有改變任何東西:(用初始化編輯代碼 – user2594166
你想從內核得到的實際結果是什麼?它只是'min'和'pos'或者'f'中的其他值是否也需要? – talonmies