Ask Your Question

How to use lambda as a parameter to parallel_for_

asked 2015-07-08 07:42:21 -0500

Oliv gravatar image

Is it possible to pass the functor to parallel_for_ as a lambda?

cv::parallel_for_(cv::Range(0, X), [&] (const cv::Range & r) {
    for (int index = r.start; index != r.end; ++index) {
        // do work

The above code fails to compile:

..\src\test.cpp: In function 'int main()':
..\src\test.cpp:29:3: error: invalid initialization of reference of type 'const cv::ParallelLoopBody&' from expression of type 'main()::<lambda(const cv::Range&)>'
C:\opencv\build\include/opencv2/core/core.hpp:4787:17: error: in passing argument 2 of 'void cv::parallel_for_(const cv::Range&, const cv::ParallelLoopBody&, double)'

I'd like to capture local variables.

edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted

answered 2017-02-28 16:54:35 -0500

Yoyo gravatar image

You need to implement a sort of adapter pattern because cv::parallel_for_ is not a template method so the implementation could be like this:

class LambdaBody : public cv::ParallelLoopBody {    
    typedef void(*LambdaParallelLoopBody)(const cv::Range & range);
    LambdaBody(LambdaParallelLoopBody body){
        _body = body;

    void operator() (const cv::Range & range) const
    LambdaParallelLoopBody _body;

and then call it like this

cv::parallel_for_(cv::Range(0, 10), LambdaBody([&](const cv::Range & range){
        std::cout << range.start << " - " << range.end << std::endl;

hope it works for you!

edit flag offensive delete link more

Question Tools



Asked: 2015-07-08 07:42:21 -0500

Seen: 1,114 times

Last updated: Jul 08 '15