从std :: vector复制到推力:: device_vector时出现未处理的异常

问题描述

尝试使用std::vector将数据从thrust::device_vector复制到thrust::copy时遇到以下错误:

tryThrustCopy.exe中0x00007FFD7FF43E49的未处理异常:Microsoft C ++异常:内存位置0x0000002CB3B9C8B0的推力:: system :: system_error。发生

我将Windows 10与Visual Studio 16,Visual C ++ 2019(版本14),CUDA 11.0一起使用,并且我的GPU驱动程序版本为455.41。

在Visual Studio的调试模式下报告错误。发布配置中的程序从命令行运行,但将在复制步骤终止。

这是我生成错误的代码。

main.cpp:

#include <vector>
#include <thrust/device_vector.h>
#include <thrust/copy.h>
#include <iostream>
#include "particle.h"

int main(int argc,char** argv)
{   

    std::vector<particle> particles(5);

    particles.at(0).x += 1; // Do something to the host vector.

    thrust::device_vector<particle> dParticles;

    dParticles.resize(particles.size());

    //Here comes the error.
    thrust::copy(particles.begin(),particles.end(),dParticles.begin());

    std::cout << "test 2 ends" << std::endl;

    return 0;
}

particle.h:

#ifndef __particle_h__
#define __particle_h__

class particle
{
private:
    

public:
    particle() : x(0),y(0) {}
    int x;
    int y;

};

#endif

通常,我试图将粒子对象的宿主向量复制到设备向量。我还发现,使用上述代码将整数向量(vector<int>)从主机复制到设备可以正常工作。

如果有人能指出我犯了一个错误,我将非常感激。我是CUDA的新手,所以也欢迎提供有关如何检查错误的任何建议。

解决方法

当我在CUDA 10.2上编译您的代码时,收到以下警告(被截断):

.../targets/x86_64-linux/include/thrust/detail/allocator/allocator_traits.inl(97): warning: calling a __host__ function from a __host__ __device__ function is not allowed

您不应在每次进行CUDA或Thrust编程时都忽略这样的警告

不幸的是,由于某种原因,我没有收到有关CUDA 11的警告。尽管如此,它还是有关实际问题的重要线索。

它可能指的是什么功能?它指的是您的构造函数:

particle() : x(0),y(0) {}

很明显,该构造函数以某种方式在设备代码中被调用(在失败的情况下)

因此,正确的做法是用以下方法装饰该构造函数:

__host__ __device__
particle() : x(0),y(0) {}

这使警告消失了(CUDA 10.2),对我来说,您的代码随后在CUDA 11上运行而没有错误。

(在CUDA 10.2上,行为是这样,我得到警告,但是即使发出警告,代码也不会错误运行。在CUDA 11.0上,我没有得到警告,但是代码在运行时出现错误,除非您正确地装饰了构造函数。因此,我假设引擎盖下的推力行为存在显着差异。)

不过,我将提供的一般CUDA编程建议是:

您在设备代码中使用的任何对象都应具有在设备代码中可以调用的任何可能的方法,并用__host__ __device__修饰。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...