Using fibers to expand a thread’s stack at runtime, part 2

This post has been republished via RSS; it originally appeared at: Microsoft Developer Blogs.

Last time, we wrote a RunOnFiber function that accepted a lambda and ran the lambda on a fiber. Since the RunOnFiber function is templated, a new copy of the function is created for each lambda. But we can reduce the code size explosion by factoring out the part that is independent of the lambda. We use a technique similar to the one we used when we wrote our own simplified version of std::function: Convert the lambda to a flat callback and a void*. The boilerplate is now in a helper function called Run­On­Fiber­Worker, and the template function type-erases the lambda into a void* and callback function. The callback function converts the void* back into the lambda and invokes it. The decomposition of the lambda into a callback and void* allows the same Run­On­Fiber­Worker to be used for all lambdas. The lambda-specific code is just in the production of the callback function. This code is not quite finished yet, because there's the case where the lambda is a functor passed by const reference, in which case we need to respect const-ness and invoke the const version of the operator() overload. There also the oddball case where the functor has an overloaded operator&. We can avoid that by using std::addressof. A little bit of additional fiddling will take care of that: Next time, we'll look at writing a Run­On­Fiber function that reports errors by means other than just the return value.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

This site uses Akismet to reduce spam. Learn how your comment data is processed.