使用推力进行简单分类不起作用 [英] simple sorting using thrust not working
问题描述
我有一个cuda推力程序,
I have a cuda thrust program as
#include <stdio.h>
#include<iostream>
#include <cuda.h>
#include <thrust/sort.h>
// main routine that executes on the host
int main(void)
{
int *a_h, *a_d; // Pointer to host & device arrays
const int N = 10; // Number of elements in arrays
size_t size = N * sizeof(int);
a_h = (int *)malloc(size); // Allocate array on host
cudaMalloc((void **) &a_d, size);// Allocate array on device
std::cout<<"enter the 10 numbers";
// Initialize host array and copy it to CUDA device
for (int i=0; i<N; i++)
{
std::cin>>a_h[i];
}
for (int i=0; i<N; i++) printf("%d %d\n", i, a_h[i]);
cudaMemcpy(a_d, a_h, size, cudaMemcpyHostToDevice);
thrust::sort(a_d, a_d + N);
// Do calculation on device:
cudaMemcpy(a_h, a_d, sizeof(int)*N, cudaMemcpyDeviceToHost);
// Print results
for (int i=0; i<N; i++) printf("%d %d\n", i, a_h[i]);
// Cleanup
free(a_h); cudaFree(a_d);
}
,但是没有提供所需的输出。
but it is not running to give the desired output.
我们是否应该使用宿主向量和设备向量对推力进行排序?
Are we supposed to use the host vector and device vector for sorting in thrust????
推荐答案
对于设备操作,您应该使用设备指针或device_vector迭代器,而不是原始指针。原始指针(指向主机内存)可以用于主机上的操作。
For device operations you should use either a device pointer, or a device_vector iterator, not raw pointers. Raw pointers (that point to host memory) can be used for operations on the host.
因此,如果您按如下方式修改代码:
So if you modify your code as follows:
#include <thrust/device_ptr.h>
...
thrust::device_ptr<int> t_a(a_d); // add this line before the sort line
thrust::sort(t_a, t_a + N); // modify your sort line
我相信它将对您有用。
您不妨阅读推力快速入门指南。特别注意这一部分:
You may wish to read the thrust quick start guide. In particular note this section:
您可能想知道当将原始指针用作Thrust函数的参数时会发生什么。像STL一样,Thrust允许这种用法,它将分派算法的主机路径。如果所讨论的指针实际上是指向设备内存的指针,则在调用函数
You may wonder what happens when a "raw" pointer is used as an argument to a Thrust function. Like the STL, Thrust permits this usage and it will dispatch the host path of the algorithm. If the pointer in question is in fact a pointer to device memory then you'll need to wrap it with thrust::device_ptr before calling the function
这篇关于使用推力进行简单分类不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!