CUDA编程入门----Thrust库简介


一、简介

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中。

Ubuntu 12.04 下 CUDA 编程

Ubuntu 12.04 安装 CUDA-5.5 

Ubuntu 11.10 上安装CUDA开发环境

Fedora 15系统下配置CUDA环境

Ubuntu 11.04 安装 NVIDIA CUDA 4.0 RC2

Linux Mint 13/Ubuntu 12.04 配置CUDA 4.2 & OpenCV 2.4.2 方法

CUDA入门教程

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

#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;
}

三、算法

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

以thrust::sort举例说明:

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

#include <thrust/sort.h>

...
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 <thrust/sort.h>

...
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 <thrust/sort.h>
#include <thrust/functional.h>

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

thrust::stable_sort(A, A + N, thrust::greater<int>());

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

本文永久更新链接地址:

相关内容