Path: utzoo!attcan!uunet!lll-winken!lll-tis!ames!mailrus!nrl-cmf!cmcl2!brl-adm!adm!ted%nmsu.csnet@relay.cs.net From: ted%nmsu.csnet@relay.cs.net Newsgroups: comp.unix.wizards Subject: alloca... Message-ID: <16126@brl-adm.ARPA> Date: 10 Jun 88 09:40:09 GMT Sender: news@brl-adm.ARPA Lines: 72 With respect to alloca, From: Neil Webber . I believe that the real solution to this class of problem lies in the constructor/destructor model of C++ and other such languages. But isn't the following idiom for co-routines useful? (and how would it be done with c++ constructors, without alloca)? #include #include /* set up a continuation with some free stack space */ #define cospawn(jb,fun,space) {if (_setjmp(jb)) fun();else alloca(space);} /* transfer from one co-routine to another, saving our context */ #define cojmp(us,them) {if (!_setjmp(us)) _longjmp(them,1);} jmp_buf A,B,C; main() { int i; void printa(); void printb(); cospawn(A,printa,1000); cospawn(B,printb,1000); for (i=0;i<5;i++) { cojmp(C,A); /* transfer to A */ printf("c\n"); /* note the return */ cojmp(C,A); printf("C\n"); } } /* print an 'a', transfer to B, then print an 'A' and transfer to B */ void printa(them) continuation them; { while (1) { printf("a ");fflush(stdout); cojmp(A,B); printf("A ");fflush(stdout); cojmp(A,B); } } /* print an 'b', transfer to C, then print an 'B' and transfer to C */ void printb(them) continuation them; { while (1) { printf("b ");fflush(stdout); cojmp(B,C); printf("B ");fflush(stdout); cojmp(B,C); } } It is of course possible to do the same by using malloc and munging on the contents of the jmp_buf, but many implementations get very paranoid when they suddenly find their stack pointer in the middle of the heap. Another alternative is for main() to allocate separate stacks as local variables of type char []. This still requires munging the jmp_buf. All techniques which require changing the jmp_buf need to know which direction the stack grows, and something about whether a push involves pre or post de(in)crement. This idiom has the advantage of not depending on the structure of a jmp_buf, nor does it depend on the detailed operation of alloca (only on the correct operation).