3 ms·
The problem with coroutines in C and C++ is that you'll have to save the stack upon a yield, and restore it later. If only C or C++ added some stack barrier pri
by amelius 12y ago
The problem with coroutines in C and C++ is that you'll have to save the stack upon a yield, and restore it later. If only C or C++ added some stack barrier primitives to the language, coroutines could (I suspect) be added more naturally.
Perhaps Rust could introduce this.
- halayli 12y agoThis is not C/C++ specific. It's how procedure calls work on x86. You don't need to save the stack if you have a stack per coroutine. Using madvise you can always let the kernel know of the memory you no longer need. So even if you allocate 1MB stack, it doesn't mean you are using 1MB of physical memory. If at some point you used 512kb then you yielded at 100kb stack usage, you can let the OS free up the difference.
- amelius 12y agoBut when the coroutine continues running again, you need to have stack space. You'd probably then have to insert special stack-switching directives into the new stack to make it work. In any case, I think it is best to just precompute the stack-size beforehand (assuming there is no recursion), and otherwise check for stack-overflow in recursive calls (and reallocate space if necessary). Pre-allocating megabytes of stack for each running coroutine sounds like madness, and a disaster waiting to happen (also, why should my stack overflow at 1M calls, when I have 64GB of main memory?)
- halayli 12y agostack space is always precomputed and static. You cannot reallocate after it overflows. On the other hand, the default stack size on linux is 8k, 1M is excessive and way more than you need in a sane program that doesn't have huge buffers on the stack. Stack is not meant to use 64GB of memory, it's meant to be small to pass arguments and allocate small buffers on it. The rest of the 64GB is used for heap allocations.