For someone who has some async experience from other languages (Python/JavaScript), when talking about async/await there is always an assumption that there is an event loop somewhere. But for C++ I have looked through the documentation and have not found anywhere talking about the event loop. Why is this the case?
For Node, it only has one default event loop. For Python you can create multiple ones if you want. But for C++ is this event loop assumed like Node? Or for some reason, do we not need it at all?
You should make sure you never block the Event Loop. In other words, each of your JavaScript callbacks should complete quickly. This of course also applies to your await 's, your Promise.
An async function can contain an await expression, that pauses the execution of the function and waits for the passed Promise's resolution, and then resumes the async function's execution and returns the resolved value. You can think of a Promise in JavaScript as the equivalent of Java's Future or C# 's Task.
The async keyword turns a method into an async method, which allows you to use the await keyword in its body. When the await keyword is applied, it suspends the calling method and yields control back to its caller until the awaited task is complete. await can only be used inside an async method.
The async and await keywords don't cause additional threads to be created. Async methods don't require multithreading because an async method doesn't run on its own thread. The method runs on the current synchronization context and uses time on the thread only when the method is active.
Python and JavaScript don't do CPU threads (well, Python can do threads, but that's not relevant here, because Python's thread stuff isn't inherently await-able). So they fake threading with "event loops".
C++ is a low-level language that knows what CPU threads are and expects to make use of them. As such, when you co_await
on some expression, you are typically awaiting on a process that is (potentially) happening in another thread.
You certainly can fake threading with an event loop, and create some awaitable type that uses event loop processing. But that's not typically what C++ programmers do with asynchronous processing.
In C++ coroutines, the way the resumption of execution of a coroutine works depends entirely on the awaitable type you're using. It governs the scheduling of the function's resumption. Most awaitables in C++ will use some form of CPU threading (the most common method being to invoke the coroutine on the thread performing the async process it is waiting on). Others may have some kind of event loop or whatever. But the point is that this is a function of the thing which produces the value you're waiting on, not the coroutine itself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With