https://zhuanlan.zhihu.com/p/146921900很好写啊。请看下例:
#include <stdio.h>
#include <setjmp.h>
struct X {
~X() { puts("~X"); }
//char buf[512];
};
#define SETJMP(e) int r = setjmp(e); printf("setjmp(%s): %d\n", #e, r)
jmp_buf a, b, c;
void fn() {
X x;
SETJMP(a);
if (r == 0) longjmp(b, 42);
}
int main() {
SETJMP(b);
if (r == 0)
fn();
else
longjmp(a, 1);
return 0;
}
C++都支持。再把char buf[512];打开,A-oh, stack smashing detected是什么鬼。嗯,setjmp(b)的时候,fn还没有被调用,没有stack frame. fn跳到main,main再跳回fn, 这个longjmp用的可是fn的堆栈框架啊。那我们学MTU setjmp, longjmp and User-Level Threads吧:We need a thread control block data structure. We need two more jump buffers MAIN and SCHEDULER.
The scheduler is simple.THREAD_YIELD() is very simple.This is so simple.Appears to be correct.
Not-So-Correct是什么鬼?The key issue is that each thread does not have its stack frame. Once it long jumps out of its environment the stack frame allocated by the system becomes invalid. The solution is simple (有种不详的预感): allocating a separate stack frame for each thread. Newer version of gcc may not allow you to modify the jump buffer (我就知道).
Aaaaa! 看现成的代码:云风的BLOG C 的 coroutine 库, 1.6k星。fiber, setcontext又是什么鬼?signal呢?没事你抛啥子exception? coroutine.c是4 years ago改的。大佬更火的是skynet - a lightweight online game framework, 9k星,我还是学Lua算了。
co-=together subroutine=子程序 routine=例行公事。我猜起名的人并不爱编程,好比某个内向恶趣味的遣唐使:“总代表上台挨拶(问候;寒暄;应酬)”。
发布于 3 分钟前
--
FROM 106.121.132.*