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



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

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

我使用的是带有Visual Studio 16、Visual C++2019(版本14(、CUDA 11.0的Windows 10,我的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;
}

粒子.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__进行装饰。

最新更新