Home » C++ » Kinect » Lambda expressions » Parallel processing » Parallel Processing and Lambda expressions in C++11 – Part 2

Parallel Processing and Lambda expressions in C++11 – Part 2

If you’ve made the changes to the code from Part 1 then you already have code that should be working dramatically faster. In the next steps I’m going to use C++ templates to further enhance the code. I love C++ templates! I try and use them whenever I can. One of the great things about them is that only the code that is actually used gets generated and compiled. And with C++11 you’ve got the ability to use lambda functions in templates. This is useful if you’re using STL. It’s also useful for us here.

Before I do that I want to show you the combined version of the Concurrency::for_each I mentioned in my last post. I’ve included the lambda expression as the last parameter rather then putting it into a separate variable first (as I said I would):

This is going to help with understanding what I’m going to do next.

At the top of DepthBasics.cpp, just after all the headers have been included, create the following template:

It will really help you to understand what this is doing if you compare it with the updated code I’ve shown at the start of this post. You’ll notice that I’ve kept all the variables UINT as before. But I’ve also added 3 new parameters: pSrc, pDst and func. These are of types TIn, TOut and TFunc respectively. The beauty of templates is that we can use the same template with different types and the compiler will work out the rest. func is actually going to be a lambda function, as I’ll show you in a minute. I’m going to use something called a Higher-order Lambda Function.

With this new template defined we’re going to change our pixel processing to the following:

If you look at the syntax of the lambda function at the end, you’ll see that we take in a UINT16 depth value (in millimetres) and then transform this into an RGBQUAD value. This is what we were doing at the beginning, but now we’re doing it in a much faster way with parallel processing. Because we’re using a lambda function that then goes on to be part of another lambda function this is called a Higher-order Lambda Function. Thanks to templating we have something that I think (please feel free to disagree!) is much easier to read and use. We’ve also opened up the way for us to do other transformations in a parallel way – such as using Color Maps or rendering Point Cloud Normals. I’m planning on doing articles about these in the future. Watch this space 🙂