這個問題很可能有一個簡單的解決方案。根據CUDA中的偏移量訪問陣列的問題
我生成的每個線程都將被初始化爲一個初始值。例如,如果我有一個字符集,char charSet[27] = "abcdefghijklmnopqrstuvwxyz"
,我產生了26個線程。所以threadIdx.0
對應於charSet[0] = a
。夠簡單。
我以爲我想出了一個辦法做到這一點,直到我檢查我的什麼的線程在做...
下面是我寫了一個示例程序:
#include "cuda_runtime.h"
#include "device_launch_parameters.h"
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
__global__ void example(int offset, int reqThreads){
//Declarations
unsigned int idx = threadIdx.x + blockIdx.x * blockDim.x;
if(idx < reqThreads){
unsigned int tid = (offset * threadIdx.x) + blockIdx.x * blockDim.x; //Used to initialize array <-----Problem is here
printf("%d ", tid);
}
}
int main(void){
//Declarations
int minLength = 1;
int maxLength = 2;
int offset;
int totalThreads;
int reqThreads;
int base = 26;
int maxThreads = 512;
int blocks;
int i,j;
for(i = minLength; i<=maxLength; i++){
offset = i;
//Calculate parameters
reqThreads = (int) pow((double) base, (double) offset); //Casting I would never do, but works here
totalThreads = reqThreads;
for(j = 1;(totalThreads % maxThreads) != 0; j++) totalThreads += 1; //Create a multiple of 512
blocks = totalThreads/maxThreads;
//Call the kernel
example<<<blocks, totalThreads>>>(offset, reqThreads);
cudaThreadSynchronize();
printf("\n\n");
}
system("pause");
return 0;
}
我的理由是,這聲明
unsigned int tid = (offset * threadIdx.x) + blockIdx.x * blockDim.x;
將允許我引入抵消。如果offset
是2,threadIdx.0 * offset = 0
,threadIdx.1 * offset = 2
,threadIdx.2 * offset = 4
等等。這絕對不會發生。當偏移上述程序的輸出工作== 1:我的數組的範圍外
1344 1346 1348 1350...
事實上,這些值的方法:
0 1 2 3 4 5...26.
但是,當偏移== 2。所以我不確定發生了什麼問題。
讚賞任何建設性意見。
我不認爲ÿ你理解cuda線程,正確地阻止概念。請通過這個[鏈接](http://docs.nvidia.com/cuda/cuda-c-programming-guide/)。 –
@SagarMasuti你能否詳細說明我的理解在哪裏? – Mlagma
我的appologies,如果我理解你錯了。根據你的解釋,你只需要26個線程,但是你在第一次迭代中啓動內核(blocks = 1,threads = 512 = 512個線程),在第二次迭代中(blocks = 2,threads = 1024 = 2048個線程) 。 –