gpt4 book ai didi

cuda - 使用推力的简单排序不起作用

转载 作者:行者123 更新时间:2023-12-01 08:00:18 25 4
gpt4 key购买 nike

我有一个 cuda 推力程序作为

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

但它没有运行以提供所需的输出。

我们应该使用主机向量和设备向量进行推力排序吗????

最佳答案

对于设备操作,您应该使用设备指针或 device_vector 迭代器,而不是原始指针。原始指针(指向主机内存)可用于主机上的操作。

所以如果你修改你的代码如下:

#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

我相信它对你有用。

不妨阅读推力quick start guide .特别注意这一部分:

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

关于cuda - 使用推力的简单排序不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25242790/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com