一、简介

Thrust开源库的简介是“code at speed of light”。光速代码的实现听上去太过夸张,但是thrust在cuda硬件加速中确实有着无比强大的功能。

Thrust是并行算法和数据结构的基于GPU CUDA的C++库。Thrust主要通过管理系统底层的功能比如memory access(内存获取)和memory allocation(内存分配)来实现加速,使得工程师们在GPU编程的环境下能更focus在算法的设计上。

Thrust的最主要特征是实现了几种数据结构和算法的高速并行计算(high performance heterogeneous parallel computing)。例如sort,reduce,scan等。

PS. 安装CUDA tooltik的时候会自动将thrust的头文件加入标准CUDA文件路径。因此应用thrust库并不需要额外安装手续。

二、Vectors

vector是C++标准程序库(STL)中的一个类。C++ STL中也有例如std::vector的vector容器(container)。Thrust中提供了两种vector container:host_vector和device_vector。host_vector会存储在host memory中而device_vector会存储在GPU device memory中。

Linux Mint 13/Ubuntu 12.04 配置CUDA 4.2 & OpenCV 2.4.2 方法 http://www.linuxidc.com/Linux/2013-10/91102.htm

以下来自NVIDIA CUDA官网的例子阐释了如何使用vector containers:

#include

#include

#include

int main(void)

{

// H has storage for 4 integers

thrust::host_vector 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 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;

}

三、算法

Thrust提供了很多的并行算法。例如thrust::sort。Thrust中的所有算法都会有host何device的版本。唯一例外的就是thrust::copy函数,它的所有iterator arguments都应该在同一个地方:要么都在host上要么都在device上。

以thrust::sort举例说明:

对于一个数组进行排序,只需一个指令即可达成:

#include

...

const int N = 6;

int A[N] = {1, 4, 2, 8, 5, 7};

thrust::sort(A, A + N);

// A is now {1, 2, 4, 5, 7, 8}

此外thrust还非常神奇地提供thrust::sort_by_key以及thrust::stable_sort_by_key能直接sort key和value存在不同地方的key-value对。

#include

...

const int N = 6;

int    keys[N] = {  1,  4,  2,  8,  5,  7};

char values[N] = {'a', 'b', 'c', 'd', 'e', 'f'};

thrust::sort_by_key(keys, keys + N, values);

// keys is now  {  1,  2,  4,  5,  7,  8}

// values is now {'a', 'c', 'b', 'e', 'f', 'd'}

正如C++标准程序库中的sort一样,thrust中的sort函数也能接受用户自定义的运算符。例如我们在functional.h中定义比较大小的运算,然后使sort时按大小顺序由大到小排列。

#include

#include

...

const int N = 6;

int A[N] = {1, 4, 2, 8, 5, 7};

thrust::stable_sort(A, A + N, thrust::greater());

// A is now {8, 7, 5, 4, 2, 1}

0b1331709591d260c1c78e86d0c51c18.png

Logo

北京人形旗下天工造物具身智能开源社区,聚焦具身天工与慧思开物两大平台

更多推荐