微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何将 std::vector<thrust::device_vector<int>> 转换为 int**?

如何解决如何将 std::vector<thrust::device_vector<int>> 转换为 int**?

我正在开发一个应用程序,在该应用程序中,先前的处理产生了一个(较短但长度可变的)std::vector(大)thrust::device_vector,每个都具有相同的长度(但该长度也是多变的)。我需要将其转换为设备上的原始指针,以将其传递给 cuda 内核。

我做了下面的过程,据我所知,应该将 rawNumberSquare 作为设备上的指针,其中 rawNumberSquare[0]rawNumberSquare[1] 每个都包含一个指向 {{1 }} 和 numberSquareOnDevice[0][0] 分别。因此,在我看来,numberSquareOnDevice[1][0] (i,j = 0,1) 都是该程序分配的所有位置,并且可以合法访问。

然而,当内核试图访问这些位置时,这些值是错误的,程序会因非法内存访问而崩溃。

rawNumberSquare[i][j]

我还尝试了所有方法,例如使用 #include "cuda_runtime.h" #include "device_launch_parameters.h" #include <stdio.h> #include<vector> #include<thrust/device_vector.h> __global__ void talkKernel( int ** in,int dimension) { int index = threadIdx.x; for (int coord = 0; coord < dimension; ++coord) printf("in[%d][%d] = %d\n",coord,index,in[coord][index]); } int main() { //print out name of GPU in case it is helpful int deviceNumber; cudaGetDevice(&deviceNumber); cudaDeviceProp prop; cudaGetDeviceProperties(&prop,deviceNumber); std::cout << prop.name << "\n"; //make a std::vector of std::vectors of ints std::vector<std::vector<int>> numberSquareOnHost{ {1,2},{3,4} }; //copy the values of each vector to the device std::vector<thrust::device_vector<int>> numberSquareDevice; for (auto& vector : numberSquareOnHost) numberSquareDevice.push_back(thrust::device_vector<int>(vector)); //copy the raw pointers to start of the device vectors to a std::vector std::vector<int*> halfRawNumberSquareOnHost(2); for ( int i = 0; i < 2 ; ++i) halfRawNumberSquareOnHost[i] = (thrust::raw_pointer_cast(numberSquareOnHost[i].data())); //copy the raw pointers ot the device thrust::device_vector<int*> halfRawNumberSquareOnDevice(halfRawNumberSquareOnHost); //get raw pointer (on the device) to the raw pointers (on the device) int** rawNumberSquare = thrust::raw_pointer_cast(halfRawNumberSquareOnDevice.data()); //call the kernel talkKernel <<<1,2 >>> ( rawNumberSquare,2); cudaDeviceSynchronize(); //ask what's up' std::cout << cudaGetErrorString(cudaGetLastError()) << "\n"; return 0; /*output: * Quadro M2200 in[0][0] = 0 in[0][1] = 0 in[1][0] = 0 in[1][1] = 0 an illegal memory access was encountered ...\vectorOfVectors.exe (process 6428) exited with code -1073740791. */ } 分配主机指针到(原始设备)int* 而不是使用 new 并使用 {{ 分配设备 std::vector<int*> halfRawNumberSquareOnHost 1}}(并用 int** rawSquareOnDevice 填充)。这没什么区别。

解决方法

您的错误在这里:

halfRawNumberSquareOnHost[i] = (thrust::raw_pointer_cast(numberSquareOnHost[i].data()));

应该是:

halfRawNumberSquareOnHost[i] = (thrust::raw_pointer_cast(numberSquareDevice[i].data()));

第一个是抓取一个主机指针(不是你当时想要的。)第二个是抓取一个设备指针。换句话说,您构建 numberSquareDevice 是有原因的,但您发布的代码实际上并未使用它。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。