I recently discussed how async-await works and I want to know if I got it correct.
Does async-await work by switching the thread's ESP stack pointer to point to a different stack frame? That would be similar to WINAPI fibres or the old Win3.1 cooperative multitasking.
For example consider this code:
int Foo() {
int y = ReadSomethingFromConsole();
int x = await DoSomethingAsync();
return x+y;
}
The call stack would look like this:
EventLoop(...);
.......
Foo();
At the point we reach the await
statement, a new task is scheduled to run in the thread pool, and await
immediately switches the ESP pointer to point to a new stack frame in which we are at the EventLoop()
function. The current stack frame's memory segment is not discarded though, just ESP is no longer pointing to it.
The event loop then runs more events, until it gets notified that the task is complete. At this point ESP is switched to point to the stack segment of the Foo()
function.
Do I understand it correctly, is this how it works?
Edit: Also how is the new stack frame created by await
? Is it copied off of some "template" stack frame snapshot, similar to a VM snapshot?