C++11 cuda中使用推力分配程序的奇怪行为
我目前正试图从代码中删除笨重的cudamalochost/cudaFreeHost的一部分。为此,我愿意只使用std::vector,但我绝对需要底层内存必须是固定的cuda内存类型 但是,使用来自推力库的C++11 cuda中使用推力分配程序的奇怪行为,c++11,cuda,iterator,thrust,C++11,Cuda,Iterator,Thrust,我目前正试图从代码中删除笨重的cudamalochost/cudaFreeHost的一部分。为此,我愿意只使用std::vector,但我绝对需要底层内存必须是固定的cuda内存类型 但是,使用来自推力库的推力::系统::cuda::实验::pinched_分配器,我面临着奇怪的行为: //STL #include <iostream> #include <string> #include <vector> #include <algorithm>
推力::系统::cuda::实验::pinched_分配器
,我面临着奇怪的行为:
//STL
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
//CUDA
#include <cuda_runtime.h>
#include <thrust/device_vector.h>
#include <thrust/transform.h>
#include <thrust/system/cuda/experimental/pinned_allocator.h>
#define SIZE 4
#define INITVAL 2
#define ENDVAL 4
//Compile using nvcc ./main.cu -o test -std=c++11
int main( int argc, char* argv[] )
{
// init host
std::vector<float,thrust::system::cuda::experimental::pinned_allocator<float> > hostVec(SIZE);
std::fill(hostVec.begin(),hostVec.end(),INITVAL);
//Init device
thrust::device_vector<float> thrustVec(hostVec.size());
//Copy
thrust::copy(hostVec.begin(), hostVec.end(), thrustVec.begin());
//std::cout << "Dereferencing values of the device, values should be "<< INITVAL << std::endl;
std::for_each(thrustVec.begin(),thrustVec.end(),[](float in){ std::cout <<"val is "<<in<<std::endl;} );
std::cout << "------------------------" << std::endl;
//Do Stuff
thrust::transform( thrustVec.begin(), thrustVec.end(), thrust::make_constant_iterator(2), thrustVec.begin(), thrust::multiplies<float>() );
//std::cout << "Dereferencing values of the device, values should now be "<< ENDVAL << std::endl;
std::for_each(thrustVec.begin(),thrustVec.end(),[](float in){ std::cout <<"val is "<<in<<std::endl;} );
std::cout << "------------------------" << std::endl;
//Copy back
thrust::copy(thrustVec.begin(), thrustVec.end(), hostVec.begin());
//Synchronize
//cudaDeviceSynchronize(); //makes the weird behaviour to go away
//Check result
//std::cout << "Dereferencing values on the host, values should now be "<< ENDVAL << std::endl;//Also makes the weird behaviour to go away
std::for_each(hostVec.begin(),hostVec.end(),[](float in){ std::cout <<"val is "<<in<<std::endl;} );
return EXIT_SUCCESS;
}
为什么从设备到主机的复制似乎失败了?然而,Nvvp显示了一个非常精细的计时图,具有正确的复制值
顺便说一下,我使用了7.5包中的NVCC/cuda/推力,以及带有titanX卡的gcc(gcc)4.8.5
提前感谢您的帮助。这是一个真正的错误,推力开发人员已经意识到了这一点,请参阅
使用github存储库中最新的1.8.3版本的推力为我解决了这个问题。我无法在任何我可以访问的平台上重现这个问题。如果在设备到主机拷贝后尝试打印向量之前添加同步调用,会发生什么情况?我还可以在gtx680(compute capability 3.0)上重现错误。实际上,添加cudaDeviceSynchronize可以使代码按预期运行。我相信推力::复制具有同步行为,但实际上文档中没有关于推力的同步/异步行为的信息:
val is 2
val is 2
val is 2
val is 2
------------------------
val is 4
val is 4
val is 4
val is 4
------------------------
val is 2
val is 4
val is 4
val is 4