Home > OS >  Can I use return from a coroutine when calling another coroutine?
Can I use return from a coroutine when calling another coroutine?

Time:08-03

Suppose that I have the followings:

Task<int> A() { co_return 1; }
Task<int> B() { co_return co_await A(); }
Task<int> C() { return A(); }

Both B and C compile just fine. So I'm leaning towards using return since it looks simpler but it feels awkward to not use co_return from a coroutine. What's the best practice?

CodePudding user response:

Well, C is not really much of a coroutine, is it? It just returns one. Well, all coroutines in C are like that from outside, I like that design choice. In Python, you would have to mark B as async and could not mark C as async (or you would have to await it twice).

Next, B is not exactly the same because you "unwrap" the integer from the task and return a new task from it, there might be some efficiency overhead of that unless the compiler can optimize through co_return co_await which I have no idea about. B is also rewritten while C is not, but unless the code is heavily templatized, the impact on compilation time should be minimal.

I would opt for C, it is the most natural, A returns a Task and you just forward it outside. It's less confusing for the reader and most optimal for the compiler, I fail to see any downsides.

  •  Tags:  
  • c
  • Related