2012-08-30 83 views
2

我想使用Thrust庫來計算CUDA中設備數組的前綴總和。 我的數組分配爲cudaMalloc()。我的要求如下:將thrust :: iterators轉換爲原始指針

main() 
{ 
    Launch kernel 1 on data allocated through cudaMalloc() 
    // This kernel will poplulate some data d. 
    Use thrust to calculate prefix sum of d. 
    Launch kernel 2 on prefix sum. 
} 

我想我的內核之間的某處使用推力,所以我需要方法的指針轉換爲設備的迭代器和back.What是錯在下面的代碼?

int main()               
{                 
    int *a;             
    cudaMalloc((void**)&a,N*sizeof(int)); 
    thrust::device_ptr<int> d=thrust::device_pointer_cast(a); 
    thrust::device_vector<int> v(N);      
    thrust::exclusive_scan(a,a+N,v);       
    return 0;             
}      
+1

這是編輯打算問一個新問題嗎? – talonmies

回答

9

從你最近編輯一個完整的工作例子是這樣的:

#include <thrust/device_ptr.h> 
#include <thrust/device_vector.h> 
#include <thrust/scan.h> 
#include <thrust/fill.h> 
#include <thrust/copy.h> 
#include <cstdio> 

int main()               
{                 
    const int N = 16; 
    int * a; 
    cudaMalloc((void**)&a, N*sizeof(int)); 
    thrust::device_ptr<int> d = thrust::device_pointer_cast(a); 
    thrust::fill(d, d+N, 2); 
    thrust::device_vector<int> v(N);      
    thrust::exclusive_scan(d, d+N, v.begin()); 

    int v_[N]; 
    thrust::copy(v.begin(), v.end(), v_); 
    for(int i=0; i<N; i++) 
     printf("%d %d\n", i, v_[i]);  

    return 0;             
} 

的事情你有錯:

  1. N沒有在任何地方定義
  2. 傳遞原始設備指針a而不是device_ptrd作爲輸入迭代器exclusive_scan
  3. 傳遞device_vectorvexclusive_scan而不是適當的迭代器v.begin()

關注細節是所有的缺乏,使這項工作。攜手它:

$ nvcc -arch=sm_12 -o thrust_kivekset thrust_kivekset.cu 
$ ./thrust_kivekset 

0 0 
1 2 
2 4 
3 6 
4 8 
5 10 
6 12 
7 14 
8 16 
9 18 
10 20 
11 22 
12 24 
13 26 
14 28 
15 30 

編輯:

thrust::device_vector.data()將返回thrust::device_ptr指向向量的第一個元素。 thrust::device_ptr.get()將返回原始設備指針。因此

cudaMemcpy(v_, v.data().get(), N*sizeof(int), cudaMemcpyDeviceToHost); 

thrust::copy(v, v+N, v_); 

是在這個例子中功能上等同的。

+0

如何從device_vector提取原始指針? –

+0

還有一件事會彈出這樣的錯誤:推力:: system :: system_error在內存位置0x0043f3a8 .. –

+0

請參閱我的編輯。基本上重新回答你已經回答和接受的問題*兩次,或許可以按順序進行投票。 – talonmies

3

轉換從cudaMalloc()使用thrust::device_pointer_cast獲得一個thrust::device_ptr您的原始指針。下面是來自推力文檔的例子:

#include <thrust/device_ptr.h> 
#include <thrust/fill.h> 
#include <cuda.h> 

int main(void) 
{ 
    size_t N = 10; 

    // obtain raw pointer to device memory 
    int * raw_ptr; 
    cudaMalloc((void **) &raw_ptr, N * sizeof(int)); 

    // wrap raw pointer with a device_ptr 
    thrust::device_ptr<int> dev_ptr = thrust::device_pointer_cast(raw_ptr); 

    // use device_ptr in Thrust algorithms 
    thrust::fill(dev_ptr, dev_ptr + N, (int) 0);  

    // access device memory transparently through device_ptr 
    dev_ptr[0] = 1; 

    // free memory 
    cudaFree(raw_ptr); 

    return 0; 
} 

使用thrust::inclusive_scanthrust::exclusive_scan計算前綴總和。

http://code.google.com/p/thrust/wiki/QuickStartGuide#Prefix-Sums

+0

我試過但不適用於我..我已經添加源代碼的問題,請看看它 –