Handmade Coroutines for Windows
In a previous post I implemented coroutines using the ucontext.h header. In this post I will show a replacement that should be much faster. I will also provide a Windows implementation.
I like to start off with some code, so here is the complete code for switching the stack in Linux:
switch_to_context:
pushq %rbp
movq %rsp, %rbp
// store rbx and r12 to r15 on the stack. these will be restored
// after we switch back
pushq %rbx
pushq %r12
pushq %r13
pushq %r14
pushq %r15
movq %rsp, (%rdi) // store stack pointer
switch_point:
// set up the other guy's stack pointer
movq %rsi, %rsp
// and we are now in the other context
// restore registers
popq %r15
popq %r14
popq %r13
popq %r12
popq %rbx
popq %rbp
retq