Component index
Section index

Component COROUTINE


Search

	/*
	    This sample shows a recursive solution used with co-routine.
	    The co-routine solve the hanoi tour problem.
	*/
	struct HTOUR {
	    int nbdisk;
	    int sizes[20];
	    HTOUR (){
	        nbdisk = 0;
	        memset (sizes,0,sizeof(sizes));
	    }
	    void fill (int n){
	        for (int i=0; i<n; i++){
	            sizes[i] = n - i;
	        }
	        nbdisk = n;
	    }
	    void dump(){
	        printf ("\t---| ");
	        for (int i=0; i<nbdisk; i++){
	            printf (" %2d",sizes[i]);
	        }
	        printf ("\n");
	    }
	};
	
	
	static void hanoi (
	    _F_COROUTINE *c,
	    HTOUR &tsrc,
	    int nbmove,         // How many disk must be moved from tsrc
	    HTOUR &ttmp,
	    HTOUR &tdst)
	{
	    if (nbmove > 1){
	        hanoi (c,tsrc,nbmove-1,tdst,ttmp);
	    }
	    tsrc.nbdisk--;
	    tdst.sizes[tdst.nbdisk] = tsrc.sizes[tsrc.nbdisk];
	    tdst.nbdisk++;
	    c->yield();
	    if (nbmove > 1){
	        hanoi (c,ttmp,nbmove-1,tsrc,tdst);
	    }
	}
	<mod>
	static void sample_coroutine3()
	{
	    glocal HTOUR t1,t2,t3;
	    glocal.t1.fill (5);
	    printf ("Starting\n");
	    glocal.t1.dump();
	    glocal.t2.dump();
	    glocal.t3.dump();
	    <obj COROUTINE co>();
	    <f run>
	        hanoi (this,glocal.t1,glocal.t1.nbdisk,glocal.t2,glocal.t3);
	    </f>
	    </obj>
	    while (co.next()){
	        printf ("State\n");
	        glocal.t1.dump();
	        glocal.t2.dump();
	        glocal.t3.dump();
	    }
	    printf ("End\n");
	    glocal.t1.dump();
	    glocal.t2.dump();
	    glocal.t3.dump();
	}
	</mod>