Are coroutines broken? (or is this some new/different behavior?)

Alvis Yardley ac.yardley at gmail.com
Mon Apr 23 17:54:18 UTC 2012


>>>>> "parrot-dev" == Patrick R Michaud <pmichaud at pobox.com> writes:

    parrot-dev> On Sat, Apr 21, 2012 at 06:48:08AM -0400, Andrew Whitworth
    parrot-dev> wrote:
    >> Techically not "broken", though it is behavior I've never quite agreed
    >> with. When a coroutine returns, it is considered "dead" and cannot be
    >> executed again. This makes them, I think, quite useless for most
    >> possible applications.
    >> 
    >> I thought there was a way to manually reset the coroutine to get it
    >> invokable again. However, looking at the code I don't see any such
    >> thing.

    parrot-dev> Rakudo uses coroutines extensively for its gather/take
    parrot-dev> construct.

    parrot-dev> The trick is to only execute clones of the coroutine itself;
    parrot-dev> the clones eventually reach the "dead" state, but the original
    parrot-dev> uninvoked coroutine is always available for producing fresh
    parrot-dev> copies to restart from.

    parrot-dev> Pm

Follwoing up on Whiteknight's and P. Michaud's advice/information, below, are
a couple of, rather simple, examples, illustrating how to clone a coroutine
and, then, call the cloned coroutine in winxed:

Example 1:

function MyCoroutine() {
    yield 1;
    yield 2;
    yield 3;
    return 4;
}

function main[main]() {
    var mycor1 = clone(MyCoroutine);
    var mycor2 = clone(MyCoroutine);
    for (int i = 0; i < 4; i++)
        say(mycor1());
    for (int i = 0; i < 4; i++)
        say(mycor2());
}

Example 2:

function MyCoroutine() {
    yield 1;
    yield 2;
    yield 3;
    return 4;
}

function main[main]() {
    var mycor = new 'FixedPMCArray'(2);
    mycor[0]  = clone(MyCoroutine);
    mycor[1]  = clone(MyCoroutine);
    for (int i = 0; i < 2; i++)
        for (int j = 0; j < 4; j++)
            say(mycor[i]());
}

-- 
Alvis


More information about the parrot-dev mailing list