首页 > 解决方案 > 如何转换 std::vector> 诠释**?

问题描述

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

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

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

#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和分配设备(并int** rawSquareOnDevicecudaMalloc填充它cudaMemcpy)。这并没有什么不同。

标签: c++stlcudathrust

解决方案


你的错误在这里:

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

它应该是:

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

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


推荐阅读