1

Can't figure out why this, seemingly recursive, invocation of readKey doesn't result in a growing call stack:

#include <future>
#include <iostream>

void readKey()
{
    std::async(std::launch::async, [](){ 
        if (getchar() != 113) // 'q' to quit
            readKey();
    });
}

int main(int, char**)
{
    readKey();
    return 0;
}

Thank you fort explaining!

:-)

6
  • 1
    How are you determining the call stack size? Commented Apr 20, 2017 at 14:02
  • 4
    No thread ever calls readKey(); more than once. Each call to std::async creates a new thread with a fresh stack. Commented Apr 20, 2017 at 14:06
  • @FrançoisAndrieux The std::future returned by async blocks in the destructor until the thread finishes. Commented Apr 20, 2017 at 14:11
  • @NethanOliver: does it also joins the thread? isn't it UB to not join it? Commented Apr 20, 2017 at 14:15
  • @AndyT That is what the block is. It waits for the thread to return(join()). Commented Apr 20, 2017 at 14:50

1 Answer 1

2

It's not a recursive call because you call it on a new thread (std::launch::async) which has a separate stack. So when you call readKey in main, it spawns a new thread where readKey will be called, and exits even not waiting for it.

Sign up to request clarification or add additional context in comments.

3 Comments

I say this is a very inefficient recursion using a thread and a full stack instead of just adding a call to the stack. The function calls itself which technically is the definition of recursion.
@RobertJacobs: technically speaking, it doesn't call itself, at least directly, it rather schedules that call, I'm sure you know what I meant
@RobertJacobs: The point of this code is not achieving high efficiency, but executing the same operation in an infinite loop. Kind of like event loop, only implemented as pseudo-recursive lambda. I saw this code in some ASIO server examples and couldn't wrap my head around it... Now, it's getting more clear! :) Thank you to all who took their time to provide explanations!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.