coroutine_example.cpp 826 Bytes
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
#include <cstdio>
#include <string>

#include <tool/coroutine.h>

using namespace std;

typedef COROUTINE<int, int> MyCoroutine;

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++)
			{
				printf("%s: Yielding %d\n", __FUNCTION__, i);
				cofunc.Yield(i);
			}
		}

		void Run()
		{
			cofunc = MyCoroutine (this, &MyClass::CountTo);
			printf("%s: Calling coroutine that will count from 1 to 5.\n", __FUNCTION__);
			cofunc.Call(5);
			while (cofunc.Running())
			{
				printf("%s: Got value: %d\n", __FUNCTION__, cofunc.ReturnValue());
				cofunc.Resume();
			}
	
			printf("%s: Done!\n", __FUNCTION__);
		}

		MyCoroutine cofunc;
};


main()
{
	MyClass obj;

	obj.Run();
	
	return 0;
}