2

为什么 setjmp 不保存堆栈?
考虑以下代码:

#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;
}

我除了代码会从 main 来回跳转到函数并每次返回打印增加的数字。
实际发生的是它打印0然后1无限次。就好像当它跳回函数时,堆栈被重置为默认值。为什么这样做?有什么办法可以让它保存堆栈吗?
我知道setjmp并且在编码风格和可读代码longjmp方面甚至比goto它更糟糕,但我现在正在试验,这段代码可能永远不会看到可用应用程序的光芒。

4

1 回答 1

2

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.

于 2011-08-28T22:31:28.810 回答