Question

Why isn't setjmp saving the stack?
Consider the following code:

#include <iostream>

jmp_buf Buf;
jmp_buf Buf2;

void MyFunction()
{
    for(int i = 0; i < 5; i++)
    {
        std::cout << i << std::endl;
        if(!setjmp(Buf))
            longjmp(Buf2, 1);
    }
}

int main (int argc, const char * argv[])
{
    while(true)
    {
        if(!setjmp(Buf2))
        {
            MyFunction();
            break;
        }
        longjmp(Buf, 1);
    }
    return 0;
}

What I except is that the code will jump back and forth from main to the function and back printing increasing number every time.
What actually happens is that it prints 0 and then 1 infinite number of times. it is as if when it jumps back into the function the stack is reset to defaults. why is it doing it? is there any way I can make it save the stack too?
I know setjmp and longjmp are even worse than goto when it comes to coding style and readable code, but I am experimenting right now, and this code will probably never see the light of a usable application.

Was it helpful?

Solution

Because unfortunately thats not how setjmp works. setjmp copies the current instruction pointer and register set into the jump buffer but it does not copy the stack (obviously be cause the stack is huge). It looks like you want to use some kind of coroutine based techniques. If you want to do this yourself checkout the ucontext procedured (ucontext.h) http://compute.cnr.berkeley.edu/cgi-bin/man-cgi?ucontext.h+3 they will help you to allocate and manage additionaly thread stacks.

or you could use something like Russ Cox's libtask (http://swtch.com/libtask/) which will help do this for you. Or if you want to do it yourself you should take a look at the libtask code (also available through that link). It's pretty easy to read so its a good resource.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top