Setjmp/longjmp in Ruby’s Continuation

2019-08-06 04:13发布

问题:

I was wondering about this while digging through the code of cont.c in Ruby’s current version. The documentation of setjmp says that calling longjmp on the jmp_buf structure after the caller of setjmp returned is an error. But, it seems that Ruby does this happily and does not crash:

https://github.com/ruby/ruby/blob/05f087c844f0e1e7cfe323edcf591de64069a289/cont.c#L522 https://github.com/ruby/ruby/blob/05f087c844f0e1e7cfe323edcf591de64069a289/cont.c#L775 (+ a couple more usages with fibers)

And I ask: how is that possible?

I did notice that the same source code uses also set/getcontext, but only with fibers or so it seems. It would seem more reasonable to me to use these functions rather than set/longjmp.