如何在 CUDA 中使用多态性 [英] How to use polymorphism in CUDA

查看:28
本文介绍了如何在 CUDA 中使用多态性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将一些物理模拟代码从 C++ 移植到 CUDA.

I am porting some physics simulation code from C++ to CUDA.

基本算法可以理解为:对向量的每个元素应用一个算子.在伪代码中,模拟可能包括以下内核调用:

The fundamental algorithm can be understood as: applying an operator to each element of a vector. In pseudocode, a simulation might include the following kernel call:

apply(Operator o, Vector v){
    ...
}

例如:

apply(add_three_operator, some_vector)

将为向量中的每个元素添加三个.

would add three to each element in the vector.

在我的 C++ 代码中,我有一个抽象基类 Operator,具有许多不同的具体实现.重要的方法是类运算符{虚拟双操作(双 x)=0;运算符 compose(运算符 lo,运算符 ro);...}

In my C++ code, I have an abstract base class Operator, with many different concrete implementations. The important method is class Operator{ virtual double operate(double x) =0; Operator compose(Operator lo, Operator ro); ... }

AddOperator 的实现可能如下所示:

The implementation for AddOperator might look like this:

class AddOperator : public Operator{
    private:
        double to_add;
    public:
        AddOperator(double to_add): to_add(to_add){}
        double operator(double x){
            return x + to_add;
        }
};

运算符类具有缩放和组合运算符具体实现的方法.这种抽象让我可以简单地将叶"运算符组合成更一般的转换.

The operator class has methods for scaling and composing concrete implementations of Operator. This abstraction allows me to simply compose "leaf" operators into more general transformations.

例如:

apply(compose(add_three_operator, square_operator), some_vector);

将添加三个然后平方向量的每个元素.

would add three then square each element of the vector.

问题是 CUDA 不支持内核中的虚拟方法调用.我目前的想法是使用模板.然后内核调用看起来像:

The problem is CUDA doesn't support virtual method calls in the kernel. My current thought is to use templates. Then kernel calls will look something like:

apply<Composition<AddOperator,SquareOperator>>
    (compose(add_three_operator, square_operator), some_vector);

有什么建议吗?

推荐答案

可能是这样的......

Something like this perhaps...

template <class Op1, class Op2>
class Composition {...}

template <class Op1, class Op2>
Composition<Op1, Op2> compose(Op1& op1, Op2& op2) {...}

template<class C>
void apply(C& c, VecType& vec){...}

这篇关于如何在 CUDA 中使用多态性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆