P
Philip Herron
I've been following http://www.chiark.greenend.org.uk/~sgtatham/coroutines.html
Trying to understand iterators and came up with this:
#include <stdio.h>
#include <stdlib.h>
enum STATUS {
YIELD_OK,
YIELD_EOF,
};
enum STATUS yield (void ** context/*, int * retval*/)
{
struct ctx {
int line;
int i;
};
struct ctx * x = (struct ctx *) *context;
if (!x)
{
x = *context = malloc (sizeof (struct ctx));
x->line = 0;
}
if (x)
switch (x->line) { case 0:;
for (x->i = 0; x->i < 10; x->i++)
{
do {/*
int it = x->i;
*retval = it;*/
x->line = __LINE__; return YIELD_OK; case __LINE__:;
} while (0);
}
}
free (*context);
*context = 0;
//*retval = -1;
return YIELD_EOF;
}
int main (int argc, char ** argv)
{
int val = 0;
int co = 0;
enum STATUS s;
for (s = yield ((void **) &co/*, &val*/);
s != YIELD_EOF;
s = yield ((void **) &co/*, &val*/))
printf ("iteration %i\n", val);
return 0;
}
I set val = 0 and don't touch it and the loop prints:
10-4-5-68:workspace redbrain$ gcc iterator.c -g -O0 -Wall
10-4-5-68:workspace redbrain$ ./a.out
iteration 32673
iteration 32673
iteration 32673
iteration 32673
iteration 32673
iteration 32673
iteration 32673
iteration 32673
iteration 32673
iteration 32673
I think the malloc in the callee is doing something funny but not really sure whats going on i know its a fairly big test case but any pointers would be great.
Thanks
--Phil
Trying to understand iterators and came up with this:
#include <stdio.h>
#include <stdlib.h>
enum STATUS {
YIELD_OK,
YIELD_EOF,
};
enum STATUS yield (void ** context/*, int * retval*/)
{
struct ctx {
int line;
int i;
};
struct ctx * x = (struct ctx *) *context;
if (!x)
{
x = *context = malloc (sizeof (struct ctx));
x->line = 0;
}
if (x)
switch (x->line) { case 0:;
for (x->i = 0; x->i < 10; x->i++)
{
do {/*
int it = x->i;
*retval = it;*/
x->line = __LINE__; return YIELD_OK; case __LINE__:;
} while (0);
}
}
free (*context);
*context = 0;
//*retval = -1;
return YIELD_EOF;
}
int main (int argc, char ** argv)
{
int val = 0;
int co = 0;
enum STATUS s;
for (s = yield ((void **) &co/*, &val*/);
s != YIELD_EOF;
s = yield ((void **) &co/*, &val*/))
printf ("iteration %i\n", val);
return 0;
}
I set val = 0 and don't touch it and the loop prints:
10-4-5-68:workspace redbrain$ gcc iterator.c -g -O0 -Wall
10-4-5-68:workspace redbrain$ ./a.out
iteration 32673
iteration 32673
iteration 32673
iteration 32673
iteration 32673
iteration 32673
iteration 32673
iteration 32673
iteration 32673
iteration 32673
I think the malloc in the callee is doing something funny but not really sure whats going on i know its a fairly big test case but any pointers would be great.
Thanks
--Phil