2016-06-27 32 views
0

當我在main函數中使用thrust :: device_vector時,我可以正確地將它傳遞給內核函數,代碼如下:如何將二維推力:: device_vector <thrust :: device_vector <int>>轉換爲原始指針

thrust::device_vector<int> device_a(2); 
thrust::host_vector<int> host_a(2); 
MyTest << <1, 2 >> >(thrust::raw_pointer_cast(&device_a[0]),device_a.size()); 
host_a = device_a; 
for (int i = 0; i < host_a.size();i++) 
cout << host_a[i] << endl; 

但我想在我的代碼中使用二維device_vector,我該如何使用它?如圖我以下代碼

__global__ void MyTest(thrust::device_vector<int>* a,int total){ 
    int idx = threadIdx.x; 
    if (idx < total){ 
     int temp = idx; 
     a[idx][0] = temp; 
     a[idx][1] = temp; 
     __syncthreads(); 
     } 

} 
void main(){ 
    thrust::device_vector<thrust::device_vector<int>> device_a(2,thrust::device_vector<int>(2)); 

    thrust::host_vector<thrust::host_vector<int>> host_a(2,thrust::host_vector<int>(2)); 

    MyTest << <1, 2 >> >(thrust::raw_pointer_cast(device_a.data()),device_a.size()); 
    host_a = device_a; 
    for (int i = 0; i < host_a.size(); i++){ 
    cout << host_a[i][0] << endl; 
    cout << host_a[i][1] << endl; 
} 
} 

回答

1

通常,推力容器主機僅不能在__device____global__和功能一起使用的類型。

使用二維數組的常用方法是將其放入一維線性內存空間,如下面的代碼所示。

__global__ void MyTest(int* a, int nrows, int ncols) { 
    int j = threadIdx.x; 
    int i = threadIdx.y; 
    if (i < nrows && j < ncols) { 
    int temp = i + j; 
    a[i * ncols + j] = temp; 
    } 

} 

int main(int argc, char** argv) { 
    int nrows = 2; 
    int ncols = 2; 
    thrust::device_vector<int> device_a(nrows * ncols); 
    MyTest<<<1, dim3(2, 2)>>>(thrust::raw_pointer_cast(device_a.data()), rows, ncols); 
    return 0; 
} 
+0

謝謝您的回答,它看起來就像如果我想使用3-d或4-d陣列,我哈瓦到這些陣列轉換爲1-d線陣,然後把它傳遞到內核函數。 – Qiong

相關問題