【问题标题】:Using functors in CUDA在 CUDA 中使用函子
【发布时间】:2013-01-08 18:49:32
【问题描述】:

我在 CUDA 中有以下类函子

class forSecondMax{
private:
    int toExclude;
public:
    __device__ void setToExclude(int val){
        toExclude = val;
    }
    __device__ bool operator () 
       (const DereferencedIteratorTuple& lhs, const DereferencedIteratorTuple& rhs) 
  {
    using thrust::get;
    //if you do <=, returns last occurence of largest element. < returns first
    if (get<0>(lhs)== get<2>(lhs) /*&& get<0>(rhs) == get<2>(rhs)*/ && get<0>(lhs) != toExclude/* && get<0>(rhs)!= toExclude */) return get<1>(lhs) < get<1>(rhs); else
    return true ;
  }

};

有没有办法从主机设置 toExclude 的值?

【问题讨论】:

  • 为什么不定义一个构造函数呢?这将是在对象实例化期间设置数据成员的规范方式,这在使用因此仿函数时发生在主机上......
  • @talonmies:你能看看这个问题stackoverflow.com/questions/14006148/…

标签: cuda thrust


【解决方案1】:

解决这个问题所需要做的就是为函子定义一个构造函数,该构造函数从参数中设置数据成员。所以你的班级看起来像这样:

class forSecondMax{
    private:
        int toExclude;
    public:
        __device__ __host__ forSecondMax(int x) : toExclude(x) {};
        __device__ __host__ bool operator () 
            (const DereferencedIteratorTuple& lhs, 
             const DereferencedIteratorTuple& rhs) 
            {
                using thrust::get;
                if (get<0>(lhs)== get<2>(lhs) && get<0>(lhs) != toExclude) 
                    return get<1>(lhs) < get<1>(rhs);
                else
                    return true ;
            }

};

[免责声明:在浏览器中编写,从未测试或编译,使用风险自负]

要在将函子传递给推力算法之前设置值,请创建函子的实例并将其传递给推力调用,例如:

forSecondMax op(10);
thrust::remove_if(A.begin(), A.end(), op);

这将在类的新实例中将数据成员toExclude 设置为值10,并在流压缩调用中使用该实例。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-08-13
    • 2013-02-13
    • 2021-09-09
    • 2011-08-09
    • 1970-01-01
    • 2021-06-18
    • 1970-01-01
    相关资源
    最近更新 更多