【问题标题】:boost::compute, passing pointer to a closureboost::compute,将指针传递给闭包
【发布时间】:2019-07-05 07:39:54
【问题描述】:

晚上好!我正在编写一个高性能应用程序并尝试使用 boost 来加速复杂的计算。

我的问题的本质:有没有办法将指向数组的外部指针(如float4_ *)传递给BOOST_COMPUTE_CLOSURE? 我想得到类似的东西:

float4_ *normals = new float4_[NORMALS_NO];
BOOST_COMPUTE_CLOSURE(void, evalNormals, (int4_ indices), (normals), {
    ...
});

【问题讨论】:

    标签: c++ pointers boost closures boost-compute


    【解决方案1】:

    好的,我终于找到了如何实现声明的选项。 首先要做的是将boost::compute::detail::device_ptr<float4_> 实例传递给函数。接下来,我们应该为 `OpenCL backend` 和 operator<< 声明一个类型名生成器,以将指针信息写入 meta_kernel 实例,该实例在闭包定义中以隐藏的方式使用。所以,代码:

    1) 传递device_ptr 实例

    ...
    #include <boost/compute/detail/device_ptr.hpp>
    ...
    float4_ *normalsData = new float4_[NORMALS_NO];
    device_ptr<float4_> normalsDataDP = normalsData;
    ...
    BOOST_COMPUTE_CLOSURE(void, evalNormals, (int4_ indices), (normalsDataDP), {
        ...
    });
    ...
    

    2) 实现类型名生成器:

    ...
    namespace boost {
        namespace compute {
            template<>
            inline const char *type_name<detail::device_ptr<float4_>>()
            {
                return "__global float4 *";
            }
        }
    }
    ...
    

    3) 实现operator&lt;&lt;

    ...
    namespace boost {
        namespace compute {
            namespace detail {
                meta_kernel &operator<<(meta_kernel &kern, 
                                        const device_ptr<float4_> &ptr)
                {
                    std::string nodes_info = kern.get_buffer_identifier<float4_>(ptr.get_buffer());
                    kern << kern.var<float4_ *>(nodes_info);
                    return kern;
                }
            }
        }
    }
    ...
    

    【讨论】:

    • 这个答案很旧,但我会对一个完整的例子感兴趣。我没有看到 device_ptr 的 ctor 或赋值运算符,它采用原始指针,只有一个缓冲区。这是如何运作的?对于要在闭包中捕获的每个指针,我是否需要 typename generatoroperator&lt;&lt;
    【解决方案2】:

    BOOST_COMPUTE_CLOSURE 的文档在库作者here 的报告中略显稀疏,但some test cases 显示了如何捕获vectors 和arrays。它实际上是透明地工作的,与标量相同。

    例如捕获vec:

    int data[] = {6, 7, 8, 9};
    compute::vector<int> vec(data, data + 4, queue);
    
    BOOST_COMPUTE_CLOSURE(int, get_vec, (int i), (vec), { return vec[i]; });
    
    // run using a counting iterator to copy from vec to output
    compute::vector<int> output(4, context);
    compute::transform(
        compute::make_counting_iterator(0),
        compute::make_counting_iterator(4),
        output.begin(),
        get_vec,
        queue);
    CHECK_RANGE_EQUAL(int, 4, output, (6, 7, 8, 9));
    

    【讨论】:

      猜你喜欢
      • 2012-05-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-03
      • 1970-01-01
      • 2018-12-31
      • 1970-01-01
      相关资源
      最近更新 更多