Thrust提供了丰富的常用并行算法。这算法的功能与STL中的非常相似,于是我们使用了相同的名称(例如thrust::sort
与std::sort
)。
所有的Thrust算法均提供了host端(主机端)和device端(设备端)的实现。当传入迭代器指向主机端时,将会调用主机端方法,当使用迭代器指向设备端时将调用设备端实现。
在Thrust的算法中,的迭代器参数指向必须在同一存储位置,或者主机端或者设备端。除了thrust::copy
,它可以任意的拷贝主机端和设备端的数据。
Transformations
Transformations会对指定输入范围内的元素进行特定操作,并将其结果存储到指定位置。如thrust::fill
thrust::fill(D.begin(), D.begin() + 7, 9); // 将vector D的前7个元素设置为9
此外transformations还包括thrust::sequence
、thrust::replace
、thrust::transform
(衍生于C++的for_each
)。完整的列表请参考文档。
下面的代码演示了几个transformation的用法。其中thrust::negate
和thrust::modulus
与C++中的仿函数定义是一样的。Thrust在thrust/functional.h
中也提供常用的仿函数,如plus
与multiplies
等。
#include <thrust/device_vector.h>
#include <thrust/transform.h>
#include <thrust/sequence.h>
#include <thrust/copy.h>
#include <thrust/fill.h>
#include <thrust/replace.h>
#include <thrust/functional.h>
#include <iostream>
int main(void)
{
// allocate three device_vectors with 10 elements
thrust::device_vector<int> X(10);
thrust::device_vector<int> Y(10);
thrust::device_vector<int> Z(10);
// initialize X to 0,1,2,3, ....
thrust::sequence(X.begin(), X.end());
// compute Y = -X
thrust::transform(X.begin(), X.end(), Y.begin(), thrust::negate<int>());
// fill Z with twos
thrust::fill(Z.begin(), Z.end(), 2);
// compute Y = X mod 2
thrust::transform(X.begin(), X.end(), Z.begin(), Y.