Stateless Lambdas and the Old Guard
Enough gossip. What I want to share with you today is a small change that was made to lambdas in the C++ compiler to allow them to be implicitly converted to function pointers. I can just hear you say, who cares?! Well again, if you forget for a moment that Windows 8 was also released you may recall this vast library called the Windows API that, by the way, Windows 8 was written in and you may also recall that a great many of these libraries were extensible by means of function pointers.
What this means is that you can now use lambdas to write these callbacks rather than having to define them elsewhere. This can introduce significant savings in complexity. Consider the TrySubmitThreadpoolCallback function from the Windows thread pool. Prior to Visual C++ 2012 if you wanted to allow a lambda to be submitted to the thread pool you would have to first create some concurrent queue and then have at least two functions. The first would queue the lambda-turned-function object before calling TrySubmitThreadpoolCallback. The second function being the actual callback function that would dequeue the function object from the concurrent queue and call it. That represents quite a lot of coding and run-time overhead just for the convenience of using lambdas.
Now thanks to the Visual C++ 2012 compiler you can use lambdas with the Windows API with no overhead whatsoever. No concurrent queue. No function objects. Just the thread pool.
TrySubmitThreadpoolCallback((PTP_CALLBACK_INSTANCE, void *)
printf("hello from the thread pool\n");
Clearly this only works for stateless lambdas as they are binary-compatible with function pointers whereas lambdas that capture variables are not. Still this represents a nice improvement for the C++ programmer on Windows. Enjoy!