coroutine support

Charles Oliver Nutter headius at headius.com
Thu Nov 12 09:56:49 PST 2009


Hot diggity!

On Thu, Nov 12, 2009 at 11:08 AM, Lukas Stadler <lukas.stadler at jku.at> wrote:
> Hi everybody!
>
> I've just checked in the first prototype of a coroutine implementation.
> It's implemented using the continuations framework, so it's not very
> speedy (~1µs per context switch in a simple example) but it allows me to
> experiment on how the API for coroutines could look like.
> This is how it currently works:
>
> public class CoroutineTest extends Coroutine {
>    public CoroutineTest(CoroutineContext context) {
>        super(context);
>    }
>
>    public static void main(String[] args) {
>        CoroutineContext context = new CoroutineContext();
>        new CoroutineTest(context);
>        new CoroutineTest(context);
>        context.start(null);
>    }
>
>    @Continuable
>    protected Object run(Object value) {
>        for (int i = 0; i < 10; i++) {
>            System.out.println(i);
>            yield(null);
>        }
>        return null;
>    }
> }

Looks pretty clean to me! I assume there's an equivalent "resume"
called from outside to pick up where the previous yield left off, yes?

> The Coroutine class is very similar to the thread class, it can either
> be subclassed or provided with a CoRunnable object.
> The main concept is that every coroutine is associated with a
> CoroutineContext when it is created. The coroutines will start to
> execute as soon as CoroutineContext.start is called and this method will
> not return unless all coroutines have finished. The coroutines are kept
> in a doubly-linked ring and the default scheduling (which can be changed
> by subclassing CoroutineContext) always just yields to the next
> coroutine in the ring.

Interesting. I guess I don't know this use case for coroutines. The
cases I need would (I believe) all be isolated CoroutineContexts that
may or may not call against each other.

> The main drawback of using a coroutine context in this way is of course
> that coroutines are tied to a specific thread - is this a problem? A
> notion of "moving" a coroutine from one context (and thread) to another
> could be introduced, but a coroutine will always need to be associated
> with a context so that we can make sure it will end properly.
> I'd be glad to hear what you guys think of this!

I'm excited to try it out! Tying to a specific thread should not be a
problem for me...I forgot what the outcome of our long coroutine
discussion was, but if I remember correctly tying to a thread was
considered one of the safer (if more limited) ways to go. And in
JRuby, there should be no cases where we need to use coroutines across
threads since Ruby itself won't do that.

Does the patch apply and build and all right now? I could try playing
with it today.

- Charlie


More information about the mlvm-dev mailing list