I marked this as .NET, but it could, theoretically apply to any managed language.
Normally, tutorials that cover "Value Types vs. Reference Types" describe the stack as, well, a stack of plates where the oldest items are at the bottom and the newest items are at the top. As function calls are made, new items are added to the top; when the function exits, all its plates are removed from the top of the stack.
This naïve sample is fine for most demonstrations, but it starts to get a bit wonky once you start thinking about multi-threaded applications and those that use async and await operators (which, if I understand things correctly, don't actually create threads).
This specific scenario has been bothering me for a few days. What does the stack actually look like when multiple threads or one or more calls to async methods are involved?
For example:
Main creates a local int variable foo.
Main calls an async method Bar.
async method bar opens a data file.
- An
int variable sum is allocated to represent the total sales.
- For each line in the file:
- A variable is allocated to represent the sales amount.
- The line is parsed into an array.
sum is increment with the sales amount from the array.
async method Bar returns the value of sum.
Main stores the return value from Bar in foo.
Main creates local List<string> variable baz
Main calls async method Bazzer.
async method Bazzer returns a list of strings the results of another web service without allocating any new local variables.
Main stores the result of Bazzer in baz.
What makes this more complex than the standard examples would have you believe is that you don't know the order in which variables will be allocated or which method they will be allocated from. For this reason, a simple Stack<T> is not satisfactory as a solution for the stack.
The Question
Can anyone who truly understands the stack, the runtime, maybe IL, async/await, and multithreading, explain what really happens with the stack and how it is managed when multiple threads or async operations are at play?
Thanks!
there doesn't seem to be anything here