Trust 提供了兩個vector容器:host_vector 與 device_vector。按照命名規則,host_vector位於主機端,device_vector位於GPU設備端。Trust的vector容器與STL中的容器類似,是通用的容器,可以存儲任何數據類型,可以動態調整大小。以下源代碼展示如何使用Thrust的vector容器。
- # include <thrust / host_vector .h>
- # include <thrust / device_vector .h>
- # include <iostream >
- int main ( void )
- {
- // H has storage for 4 integers
- thrust :: host_vector <int > H (4);
- // initialize individual elements
- H [0] = 14;
- H [1] = 20;
- H [2] = 38;
- H [3] = 46;
- // H. size () returns the size of vector H
- std :: cout << "H has size " << H. size () << std :: endl ;
- // print contents of H
- for ( int i = 0; i < H. size (); i ++)
- std :: cout << "H[" << i << "] = " << H[i] << std :: endl ;
- // resize H
- H. resize (2) ;
- std :: cout << "H now has size " << H. size () << std :: endl ;
- // Copy host_vector H to device_vector D
- thrust :: device_vector <int > D = H;
- // elements of D can be modified
- D [0] = 99;
- D [1] = 88;
- // print contents of D
- for ( int i = 0; i < D. size (); i ++)
- std :: cout << "D[" << i << "] = " << D[i] << std :: endl ;
- // H and D are automatically deleted when the function returns
- return 0;
- }
如這個例子所示,運算符”=”可以用來復制host_vector到
device_vector(反之亦然)。 運算符”=”也可以用來復制host_vector到host_vector或device_vector到device_vector。同樣device_vector訪問單個元素可以使用標准的括號表示法。但是,由於每次訪問需要調用cudaMemcpy,應謹慎使用。下面我們將看看一些更有效的技術。
初始化所有向量的元素為特定值、或從一個vector向另一個拷貝特定值,是非常常用的技術。Thrust提供了一些方法可以完成這些種操作。
- # include <thrust / host_vector .h>
- # include <thrust / device_vector .h>
- # include <thrust / copy .h>
- # include <thrust / fill .h>
- # include <thrust / sequence .h>
- # include <iostream >
- int main ( void )
- {
- // initialize all ten integers of a device_vector to 1
- thrust :: device_vector <int > D(10 , 1);
- // set the first seven elements of a vector to 9
- thrust :: fill (D. begin () , D. begin () + 7, 9);
- // initialize a host_vector with the first five elements of D
- thrust :: host_vector <int > H(D. begin () , D. begin () + 5);
- // set the elements of H to 0, 1, 2, 3, ...
- thrust :: sequence (H. begin () , H. end ());
- // copy all of H back to the beginning of D
- thrust :: copy (H. begin () , H. end () , D. begin ());
- // print D
- for ( int i = 0; i < D. size (); i ++)
- std :: cout << "D[" << i << "] = " << D[i] << std :: endl ;
- return 0;
- }
這里我們看到了fill、copy、sequence的使用方法。copy函數可以用來拷貝主機端或者設備端的數據到另外一個vector。與STL中的類似,fill用於簡單的向一段元素賦特定值。sequence可以用來生成等差數列。
Thrust命名空間
你可能會注意到在我們的例子中使用了thrust::host_vector 或 thrust::copy的字段。其中thrust::告訴編譯器在thrust命名空間中查找函數與類。命名空間是一個很好的方式避免命名重復。例如,thrust::copy就可以與STL中的std::copy區別開來。C++的命名空間允許我們使用這兩個copy函數。