coroutine_example.cpp 963 Bytes
Newer Older
1 2 3 4 5 6 7
#include <cstdio>
#include <string>

#include <tool/coroutine.h>

typedef COROUTINE<int, int> MyCoroutine;

8 9 10 11 12 13 14 15 16 17
class MyClass
{
public:
    int CountTo( int n )
    {
        printf( "%s: Coroutine says hi. I will count from 1 to %d and yield each value.\n",
                __FUNCTION__,
                n );

        for( int i = 1; i <= n; i++ )
18
        {
19 20
            printf( "%s: Yielding %d\n", __FUNCTION__, i );
            cofunc.Yield( i );
21
        }
22 23 24 25 26 27 28
    }

    void Run()
    {
        cofunc = MyCoroutine( this, &MyClass::CountTo );
        printf( "%s: Calling coroutine that will count from 1 to 5.\n", __FUNCTION__ );
        cofunc.Call( 5 );
29

30
        while( cofunc.Running() )
31
        {
32 33
            printf( "%s: Got value: %d\n", __FUNCTION__, cofunc.ReturnValue() );
            cofunc.Resume();
34 35
        }

36 37 38 39
        printf( "%s: Done!\n", __FUNCTION__ );
    }

    MyCoroutine cofunc;
40 41 42
};


43
main() {
44
    MyClass obj;
45

46 47 48 49
    obj.Run();

    return 0;
}