|
//thrust::reduce或其他函数操作的数据来源:device_ptr封装
//1、thrust::device_vector<type>直接定义的
//2、cudaMalloc与cudaMemcpy来的需要用thrust::device_ptr封装一下
//thrust中还定义了device_ptr指针类型,当传入函数的指针是指向device端的内存时,需要用device_ptr进行封装
- #include <thrust/device_vector.h>
- #include <iostream>
- using namespace std;
- //thrust::reduce或其他函数操作的数据来源:
- //1、thrust::device_vector<type>直接定义的
- //2、cudaMalloc与cudaMemcpy来的需要用thrust::device_ptr封装一下
- //thrust中还定义了device_ptr指针类型,当传入函数的指针是指向device端的内存时,需要用device_ptr进行封装
- int main(void){
- float array[6] = { 3, 1, 2, 3, 5, 4 };
- float *dev_array = 0;
- cudaMalloc(&dev_array, sizeof(float) * 6);
- cudaMemcpy(dev_array, array, sizeof(float) * 6, cudaMemcpyHostToDevice);
- //dev_array :指向GPU设备内存块的指针 需要用device_ptr进行封装 否则:段错误 (核心已转储)
- thrust::device_ptr<float> dev_ptr(dev_array); // 这里是赋值吧? dev_ptr= dev_array 并封装
-
- cout << "看地址的值:" << dev_array << endl;
- cout << "device_ptr看地址的值:" << dev_ptr << endl;
- //从device_ptr中提取“原始”指针需要使用raw_pointer_cast函数
- float *raw_pointer_dev_array=thrust::raw_pointer_cast(dev_ptr);
- cout << "raw_device_ptr看地址的值:" << raw_pointer_dev_array << endl;
- //由于dev_array指向device端,不能直接作为参数,需要对其封装 否则:段错误 (核心已转储)
- int sum = thrust::reduce(dev_ptr, dev_ptr + 6, (int) 0, thrust::plus<int>());
- cout << "求和的结果=" << sum << endl;
- thrust::host_vector<float> hvec(6, 2);
- thrust::device_vector<float> dvec;
- dvec=hvec; //device vector和 host vector可以直接用等号进行传递,对应于cudaMemcpy的功能
- //此时的参数是迭代器,不用也不能用device_ptr对其封装
- sum = thrust::reduce(dvec.begin(), dvec.end(), (int) 0, thrust::plus<int>());
- cout << "求和的结果=" << sum << endl;
- //上述的两种函数的调用方法也存在host端的版本,传入的指针或者迭代器都是host端数据
- // thrust::reduce(array, array + 6);
- // thrust::reduce(hvec.begin(), hvec.end());
-
- return 0;
- }
复制代码
|
|