alloca...

ted%nmsu.csnet at relay.cs.net ted%nmsu.csnet at relay.cs.net
Fri Jun 10 19:40:09 AEST 1988


With respect to alloca,

    From: Neil Webber <nw at palladium.uucp>
.
    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 <stdio.h>
#include <setjmp.h>

/* 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).



More information about the Comp.unix.wizards mailing list