2015-08-28 111 views
0

如何通過推力從Global訪問指針。通過推力從__Global__訪問指針

thrust::device_vector<int> testvec; 

int *send_data = thrust::raw_pointer_cast(&testvec[0]); 

<< <1, 1 >> > (send_data, raw_ptr); 

我能夠與全球

工作中使用SEND_DATA。我無法檢索它

thrust::device_ptr<int> dev_ptr = thrust::device_pointer_cast(raw_ptr); 

printf("addr: %p\n", dev_ptr); <<< i am able to retrieve pointer address but not data 
+1

你需要非常發佈[MCVE] –

回答

2

有許多方法可以從主機訪問設備數據。你可以:

  1. 複製回來隱含(在下面的代碼所示)
  2. 將它複製回用thrust::copy
  3. 複製回來cudaMemcpy
  4. 您也可以搶device_vector元素直接在主機代碼 - 推力將在引擎蓋下爲你做必要的複製,然後將它們打印出來。

下面的代碼演示了這四種方法 - 我敢肯定有其他方法或變體以及:

$ cat t897.cu 
#include <thrust/device_vector.h> 
#include <thrust/copy.h> 

#define DSIZE 10 

__global__ void kernel(int *send_data, int sz){ 

    int idx = threadIdx.x+blockDim.x*blockIdx.x; 

    if (idx < sz) send_data[idx]++; 
} 

int main(){ 

    thrust::device_vector<int> testvec(DSIZE); 
    int *send_data = thrust::raw_pointer_cast(&(testvec[0])); 

    kernel<<<1,DSIZE>>>(send_data, DSIZE); 
// method 1 
    thrust::host_vector<int> hvec1 = testvec; 
    for (int i = 0; i < DSIZE; i++) printf("%d: %d\n", i, hvec1[i]); 
// method 2 
    thrust::host_vector<int> hvec2(DSIZE); 
    thrust::copy(testvec.begin(), testvec.end(), hvec2.begin()); 
    for (int i = 0; i < DSIZE; i++) printf("%d: %d\n", i, hvec2[i]); 
// method 3 
    int *hvec3 = (int *)malloc(DSIZE*sizeof(int)); 
    cudaMemcpy(hvec3, send_data, DSIZE*sizeof(int), cudaMemcpyDeviceToHost); 
    for (int i = 0; i < DSIZE; i++) printf("%d: %d\n", i, hvec3[i]); 
// method 4 
    for (int i = 0; i < DSIZE; i++) { int temp = testvec[i]; printf("%d: %d\n", i, temp);} 
} 
$ nvcc -o t897 t897.cu 
$ ./t897 
0: 1 
1: 1 
2: 1 
3: 1 
4: 1 
5: 1 
6: 1 
7: 1 
8: 1 
9: 1 
0: 1 
1: 1 
2: 1 
3: 1 
4: 1 
5: 1 
6: 1 
7: 1 
8: 1 
9: 1 
0: 1 
1: 1 
2: 1 
3: 1 
4: 1 
5: 1 
6: 1 
7: 1 
8: 1 
9: 1 
0: 1 
1: 1 
2: 1 
3: 1 
4: 1 
5: 1 
6: 1 
7: 1 
8: 1 
9: 1 
$ 
+0

謝謝:) – Rk1