这是对我有用的东西。您可以一次性创建使用自定义 malloc 的自定义执行策略和分配器:
#include <thrust/system/cuda/execution_policy.h>
#include <thrust/system/cuda/memory.h>
#include <thrust/system/cuda/vector.h>
#include <thrust/remove.h>
// create a custom execution policy by deriving from the existing cuda::execution_policy
struct my_policy : thrust::cuda::execution_policy<my_policy> {};
// provide an overload of malloc() for my_policy
__host__ __device__ void* malloc(my_policy, size_t n )
{
printf("hello, world from my special malloc!\n");
return thrust::raw_pointer_cast(thrust::cuda::malloc(n));
}
// create a custom allocator which will use our malloc
// we can inherit from cuda::allocator to reuse its existing functionality
template<class T>
struct my_allocator : thrust::cuda::allocator<T>
{
using super_t = thrust::cuda::allocator<T>;
using pointer = typename super_t::pointer;
pointer allocate(size_t n)
{
T* raw_ptr = reinterpret_cast<T*>(malloc(my_policy{}, sizeof(T) * n));
// wrap the raw pointer in the special pointer wrapper for cuda pointers
return pointer(raw_ptr);
}
};
template<class T>
using my_vector = thrust::cuda::vector<T, my_allocator<T>>;
int main()
{
my_vector<int> vec(10, 13);
vec.push_back(7);
assert(thrust::count(vec.begin(), vec.end(), 13) == 10);
// because we're superstitious
my_policy policy;
auto new_end = thrust::remove(policy, vec.begin(), vec.end(), 13);
vec.erase(new_end, vec.end());
assert(vec.size() == 1);
return 0;
}
这是我的系统上的输出:
$ nvcc -std=c++11 -I. test.cu -run
hello, world from my special malloc!
hello, world from my special malloc!
hello, world from my special malloc!
hello, world from my special malloc!
你可以变得更喜欢并使用thrust::pointer<T,Tag>
要合并的包装器my_policy
成习惯pointer
类型。这样就可以达到标记的效果my_vector
的迭代器与my_policy
而不是 CUDA 执行策略。这样,您就不必为每个算法调用提供显式执行策略(如示例中调用thrust::remove
)。相反,Thrust 只需查看类型即可知道使用您的自定义执行策略my_vector
的迭代器。