I recently fiddled around a bit with how one might implement cooperative threading in perl 6 using call-with-current-continuation (callcc), so I thought I'd share it with you

(since continuations are often poorly understood, more examples is always better :-)

This is assuming callcc exists and that the continuation is topic inside it; if that's not a built-in then callcc can no doubt be defined using whatever is available to make continuations.

Enjoy!


my @queue;


sub thread_exit () {
        shift(@queue)(undef);
        exit;
}

sub thread_new (&code) {
        push @queue, callcc {
                unshift @queue, $_;
                code;
                thread_exit;
        }
}

sub thread_yield () {
        if @queue {
                my $prev = callcc shift @queue;
                push @queue, $prev  if $prev;
        }
}



thread_new {
        for 1..10 -> $i {
                print "foo: $i\n";
                thread_yield;
        }
}

thread_new {
        for 1..10 -> $i {
                print "bar: $i\n";
                thread_yield;
        }
}


thread_new { for 1..10 -> $i { print "baz: $i\n"; thread_yield; } }

thread_exit;


-- Matthijs van Duin -- May the Forth be with you!

Reply via email to