// // MYCoroutineTest.m // Coroutines // // Created by Jens Alfke on 4/29/08. // Copyright 2008 __MyCompanyName__. All rights reserved. // #import "MYCoroutine.h" #import "CoroX.h" @interface CoroTest1 : MYCoroutine { int value; } @property int value; @end @interface CoroTest2 : CoroTest1 @end CoroTest1 *firstCoro, *secondCoro; @implementation CoroTest2 - (void) main { int num = 0; NSLog(@"secondTask created with value %d", self.value); while (1) { NSLog(@"secondTask: %d %d", self.bytesLeftOnStack, num++); [firstCoro resume]; } } @end @implementation CoroTest1 @synthesize value; - (void) regress: (int)depth { char useUpSpace[1024]; useUpSpace[0] = 0; NSLog(@"infinite regress: depth=%i, stack space=%d", depth,self.bytesLeftOnStack); if( [[MYCoroutine currentCoroutine] stackSpaceAlmostGone] ) NSLog(@"infinite regress: bailing out!"); else [self regress: depth+1]; } - (void) main { int num = 0; NSLog(@"firstTask created with value %d", self.value); secondCoro = [[CoroTest2 alloc] init]; secondCoro.name = @"second"; secondCoro.value = 2; while ( num < 100 ) { NSLog(@"firstTask: %d %d", self.bytesLeftOnStack, num++); [secondCoro resume]; } [secondCoro release]; NSLog(@"*** TESTING STACK LIMITS ***"); [self regress: 1]; [[MYCoroutine mainCoroutine] resume]; } + (void) test { NSLog(@"*** TESTING COROUTINES ***"); firstCoro = [[CoroTest1 alloc] init]; firstCoro.name = @"first"; firstCoro.value = 1; [firstCoro resume]; NSLog(@"Returned from coroutines; exiting"); [firstCoro release]; } @end @interface Generator : MYCoroutine { int _count; } - (id) initWithCount: (int)count; @end @implementation Generator - (id) initWithCount: (int)count { self = [super init]; if (self != nil) { _count = count; } return self; } - (void) main { for( int i=1; i<=_count; i++ ) [MYCoroutine yieldToCaller: [NSNumber numberWithInt: i]]; } + (void) test { NSLog(@"*** TESTING GENERATOR ***"); Generator *g = [[Generator alloc] initWithCount: 10]; id value; while( nil != (value = [g call]) ) NSLog(@"Generator yielded %@",value); NSLog(@"Generator returned nil"); } @end int main() { NSAutoreleasePool *pool = [NSAutoreleasePool new]; NSLog(@"Starting test..."); [MYCoroutine setDefaultStackSize: kCoroX_minStackSize]; [CoroTest1 test]; [Generator test]; NSLog(@"FINISHED"); [pool drain]; }