我想使用Thrust库来计算CUDA中设备数组的前缀和.我的数组已分配cudaMalloc().我的要求如下:
main()
{
Launch kernel 1 on data allocated through cudaMalloc()
// This kernel will poplulate some data d.
Use thrust to calculate prefix sum of d.
Launch kernel 2 on prefix sum.
}
Run Code Online (Sandbox Code Playgroud)
我想在我的内核之间的某处使用Thrust所以我需要方法将指针转换为设备迭代器并返回.下面的代码有什么问题?
int main()
{
int *a;
cudaMalloc((void**)&a,N*sizeof(int));
thrust::device_ptr<int> d=thrust::device_pointer_cast(a);
thrust::device_vector<int> v(N);
thrust::exclusive_scan(a,a+N,v);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
最新编辑的完整工作示例如下所示:
#include <thrust/device_ptr.h>
#include <thrust/device_vector.h>
#include <thrust/scan.h>
#include <thrust/fill.h>
#include <thrust/copy.h>
#include <cstdio>
int main()
{
const int N = 16;
int * a;
cudaMalloc((void**)&a, N*sizeof(int));
thrust::device_ptr<int> d = thrust::device_pointer_cast(a);
thrust::fill(d, d+N, 2);
thrust::device_vector<int> v(N);
thrust::exclusive_scan(d, d+N, v.begin());
int v_[N];
thrust::copy(v.begin(), v.end(), v_);
for(int i=0; i<N; i++)
printf("%d %d\n", i, v_[i]);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
你弄错了:
N 没有定义任何地方a而不是device_ptr d作为输入迭代器exclusive_scandevice_vector v给exclusive_scan而不是适当的迭代器v.begin()对细节的关注是缺乏使这项工作所缺乏的.并且它的工作:
$ nvcc -arch=sm_12 -o thrust_kivekset thrust_kivekset.cu
$ ./thrust_kivekset
0 0
1 2
2 4
3 6
4 8
5 10
6 12
7 14
8 16
9 18
10 20
11 22
12 24
13 26
14 28
15 30
Run Code Online (Sandbox Code Playgroud)
编辑:
thrust::device_vector.data()将返回thrust::device_ptr指向向量的第一个元素的a.thrust::device_ptr.get()将返回原始设备指针.因此
cudaMemcpy(v_, v.data().get(), N*sizeof(int), cudaMemcpyDeviceToHost);
Run Code Online (Sandbox Code Playgroud)
和
thrust::copy(v, v+N, v_);
Run Code Online (Sandbox Code Playgroud)
在这个例子中功能相同.
| 归档时间: |
|
| 查看次数: |
6244 次 |
| 最近记录: |