Is nested coroutines safe?

Hi

Since coroutine is a good way to handle IO calls, I like to use it to deal with IO,WWW etc.

Now problem comes, is that safe?

Some says it’s no big deal because it’s a simulated multi-thread thing, so it would not cause real multi-thread problems like we met, just use it like a normal call. And some says it’s extremely dangerous if we misuse it, that will lead our code acts weird and hard to debug.

IEnumerator Start(){
		    yield return StartCoroutine(func1);
            yield return StartCoroutine(func2);
            yield return StartCoroutine(func3);
	}
IEnumerator func1(){
        if(something)
		    yield return StartCoroutine(func4);
        
        yield return StartCoroutine(func5);
	}
//etc

Your example is safe because you are yielding coroutines : func2 will not start before func1 has finished.

What is very dangerous if one is not aware is simultaneous coroutines : the order of execution in each frame is not guaranteed.

Example :

void Start ()
{
    StartCoroutine ( Foo ( 0, 2 ) ); //print all even numbers until 100, one per frame
    StartCoroutine ( Foo ( 1, 2 ) ); //print all odd numbers until 100, one per frame
}

IEnumerator Foo ( int i, int step )
{
    while ( i < 100 )
    {
       Debug.Log ( i );
       i += step;
       yield return null;
    }
}

The routines’ execution order is not guaranteed, it could debug 87 before 86 for example.