c++taskc++-cxppl

What are the benefits of returning a task from a function?


I've seen create_task used in a couple ways:

void Bob()
{
    create_task() { /* do stuff */ }.then([](){ /* do more stuff */ });
}

and

task<void> Bob()
{
    return create_task() { /* do stuff */ }.then([](){ /* do more stuff */ });
}

Why bother returning the task (in the second example) when asynchronous behavior can be achieved with either approach?

Clarification: I'm not asking about the void return type specifically. It could be an int, object, or something else.


Solution

  • void/task<void> is a special case here, because you can magic a void from nowhere. You couldn't do the same with a int, std::string or similar.

    void Bob()
    {
        create_task() { /* do stuff */ }.then([](){ /* do more stuff */ });
    }
    

    After this has returned /* do stuff */ and /* do more stuff */ have started, and any handle on their progress is discarded.

    task<void> Bob()
    {
        return create_task() { /* do stuff */ }.then([](){ /* do more stuff */ });
    }
    

    After this has returned /* do stuff */ and /* do more stuff */ have started, and you have a handle to wait for them to finish.

    int Alice()
    {
        return create_task() { /* do stuff */ }.then([](){ /* do more stuff */ return 42; }).get();
    }
    

    After this has returned /* do stuff */ and /* do more stuff */ have finished, with a final result available.

    task<int> Alice()
    {
        return create_task() { /* do stuff */ }.then([](){ /* do more stuff */ return 42; });
    }
    

    After this has returned /* do stuff */ and /* do more stuff */ have started, and you have a handle to wait for them to finish, and get the result.