Thrust device_malloc and device_new
使用推力
对于
"device_new implements the placement new operator for types resident
in device memory. device_new calls T's null constructor on a array of
objects in device memory. No memory is allocated by this function."
我不了解...
如果计划将Thrust用于其他用途,则
对于
1 2 | template<typename T> device_ptr< T > thrust::device_new (device_ptr< void > p, const size_t n = 1) |
p: A device_ptr to a region of device memory into which to construct
one or many Ts.
基本上,如果已经分配了内存,则可以使用此功能。将仅调用默认构造函数,这将返回强制转换为T的类型的
另一方面,以下方法分配内存并返回
1 2 | template<typename T > device_ptr< T > thrust::device_new (const size_t n = 1) |
所以我想我发现了device_new
的一个很好的用途
从根本上讲,这是初始化对象并将其复制到设备上的一种更好的方法,同时在主机上保留指向它的指针。
所以不要这样做:
1 2 3 4 5 | Particle *dev_p; cudaMalloc((void**)&(dev_p), sizeof(Particle)); cudaMemcpy(dev_p, &p, sizeof(Particle), cudaMemcpyHostToDevice); test2<<<1,1>>>(dev_p); |
我可以做到:
1 2 | thrust::device_ptr<Particle> p = thrust::device_new<Particle>(1); test2<<<1,1>>>(thrust::raw_pointer_cast(p)); |