use local variables in coroutine

aresqi wrote on Tuesday, July 04, 2006:

hello richard

Do you kown protothread by Adam Dunkels? It’s similar to coroutine and is more mature, i think. May be we can expand coroutine based on that.

I have a way to use local variables in each coroutines.

1. we add a field of   void *  pVar         in corCRCB and the initial value is NULL
2. when we enter a coroutine and if pVar is NULL , then we enter the coroutine first time , so we can malloc some space for our local variables. But how many space is machine and compiler dependent.
3. all local variable must use pointers which can point to a space return by malloc.

for example

void vACoRoutineFunction( xCoRoutineHandle xHandle, unsigned portBASE_TYPE uxIndex )
    {

        //define local variables here
        //do it before crSTART
        int *a,*b;   //we need 2 int variables
        void **c;    //we need 1 void* variable

        void *pMalloc

        if (xHandle->pVar == NULL)
        {
            pMalloc = pvPortMalloc( (sizeof)int + (sizeof)int + (sizeof)(void *) );
            if (pMalloc)
            {
                a = pMalloc;
                b = pMalloc +1 //in 32bit machine
                c = pMalloc +1 //in 32bit machine
                xHandle->pVar = pMalloc;
            }

        }
        else
        {
            pMalloc = xHandle->pVar;
            a = pMalloc;
            b = pMalloc +1 //in 32bit machine
            c = pMalloc +1 //in 32bit machine
        }

        // Co-routines must start with a call to crSTART().
        crSTART( xHandle );

        for( ;; )
        {
            *a = 10;
            // It is fine to make a blocking call here,
            crDELAY( xHandle, 10 );

            //we can use local variables now
            if (*a == 10)
            {
                …
            }

        }

        // Co-routines must end with a call to crEND().
        crEND();
    }

rtel wrote on Tuesday, July 04, 2006:

I have seen older versions of protothreads, but not the latest.

Your idea is quite neat, but I’m not sure if it has many advantages over declaring the variables static in an array, as per the examples.  Both ways will convert to code that uses a pointer offset, but the array version will be more portable (probably) with respect to data sizes and byte alignment of pointers.

Regards.