Component index
Section index

Component COROUTINE


Search

	/*
	    The following code presents a very simple coroutine, but shows
	    how we can interact.
	*/
	static void sample_costatus(COROUTINE &co, const char *msg)
	{
	    printf ("%s Status idle=%d running=%d done=%d\n"
	        ,msg,co.is_idle(),co.is_running(),co.is_done());
	}
	
	<mod>
	static void sample_coroutine1()
	{
	    glocal int result=-1;
	    <obj COROUTINE co>();
	    <f run>
	        printf ("\tStarting\n");
	        for (int i=0; i<5; i++){
	            glocal.result = i;
	            if (yield()==-1) break;
	        }
	        printf ("\tEnding\n");
	    </f>
	    </obj>
	    sample_costatus(co,"Initial");
	    // First run
	    while (co.next()){
	        printf ("\t\tresult = %d\n",glocal.result);
	    }
	    sample_costatus(co,"End first run");
	    // Second run
	    co.restart();
	    sample_costatus(co,"After restart");
	    while (co.next()){
	        printf ("\t\tresult = %d\n",glocal.result);
	    }
	    sample_costatus(co,"End second run");
	    // Third run, but short
	    co.restart();
	    sample_costatus(co,"After second restart");
	    for (int i=0; i<3 && co.next(); i++){
	        printf ("\t\tresult = %d\n",glocal.result);
	    }
	    co.stop();
	    sample_costatus(co,"End third run");
	    // Fourth run, with a restart in the middle
	    co.restart();
	    sample_costatus(co,"After third restart");
	    bool restart_done = false;
	    while (co.next()){
	        printf ("\t\tresult = %d\n",glocal.result);
	        if (glocal.result == 2 && !restart_done){
	            restart_done = true;
	            co.restart();
	        }
	    }
	    sample_costatus(co,"End fourth run");
	    // Now we just start another run, but abort and exits.
	    printf ("\t\tCurrent result=%d\n",glocal.result);
	    // Calling next() after the end has no effect.
	    co.next();
	    co.restart();
	    co.next();
	    printf ("\t\tLast result=%d\n",glocal.result);
	}
	</mod>