1. 简介
Thrust是基于标准模板库(Standard Template Library,STL)的 MXMACA® C++模板库。 Thrust支持通过与MXMACA C完全互通的高级接口,以最少的编程工作量实现高性能并行应用程序。
Thrust 提供了丰富的数据并行原语集合,如扫描(scan),排序(sort),归约(reduce)等,这些原语可以组合在一起,以简洁、可读的源代码实现复杂的算法。 通过用这些高级抽象描述计算,可以让Thrust自由、自动地选择最有效的实现。 因此,Thrust可用于MXMACA应用程序的快速原型设计(最重要的是程序员生产力),也可用于生产(稳健性和绝对性能至关重要)。 本文档介绍了如何使用Thrust开发MXMACA应用程序。 即使C++或MXMACA经验有限,也适用于本教程。
1.1. 安装
安装MXMACA工具包会将Thrust头文件复制到系统标准的MXMACA include目录。 由于Thrust是头文件的模板库,因此无需进一步安装即可使用Thrust。
# header location:
${MACA_PATH}/include/thrust
${MACA_PATH}/include/cub
1.2. Hello thrust
下面展示了如何在CMake项目中使用Thrust。
CMakeLists.txt
project(example)
cmake_minimum_required(VERSION 3.16)
# maca toolkits path
set(MACA_PATH $ENV{MACA_PATH})
# thrust path in maca toolkits
set(thrust_src_dir ${MACA_PATH}/include)
set(example_target thrust.example)
set(example_src example.cpp)
enable_language(CXX)
add_compile_options( -x maca -std=c++17 -fPIC
--maca-device-lib-path=${MACA_PATH}/lib/
--maca-device-lib=maca_mathlib.bc
--maca-device-lib=maca_kernellib.bc
--maca-host-lib-path=${MACA_PATH}/lib/
--maca-host-lib=maca_mathlib_host.bc
)
add_executable(${example_target} "${example_src}")
target_include_directories(${example_target} PRIVATE ${thrust_src_dir})
example.cpp
// Example.Application Using C and Thrust: copy
#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(size_t i = 0; i < D.size(); i++)
std::cout << "D[" << i << "] = " << D[i] << std::endl;
return 0;
}
将 example.cpp 和 CMakeLists.txt 存储在一起,运行 build 命令:
export ${MACA_PATH}=your/maca/toolkits/path
export CXX=${MACA_PATH}/mxgpu_llvm/bin/mxcc
mkdir build
cmake -B build .
cmake --build build -j
thrust.example 二进制文件将出现在 build 目录中。