Skip to content

Instantly share code, notes, and snippets.

@jnthn
Created February 22, 2017 21:31
Show Gist options
  • Save jnthn/49bf86b9ece4ff9a943e813daafba020 to your computer and use it in GitHub Desktop.
Save jnthn/49bf86b9ece4ff9a943e813daafba020 to your computer and use it in GitHub Desktop.
Iterator.pm6
my module Concurrent is export(:oop) {
class Iterator does Iterator {
has $!target-iterator;
has $!lock;
has int $!reached-end = 0;
has $!exception;
method new(Iterable:D $target) {
self.bless(:$target)
}
submethod BUILD(:$target) {
$!target-iterator = $target.iterator;
$!lock = Lock.new;
}
method pull-one() {
$!lock.protect: {
if $!reached-end {
IterationEnd
}
elsif $!exception {
$!exception.rethrow
}
else {
my \pulled = $!target-iterator.pull-one;
CATCH { $!exception = $_ }
$!reached-end = 1 if pulled =:= IterationEnd;
pulled
}
}
}
}
}
proto concurrent-iterator($) is export(:proc) { * }
multi concurrent-iterator(Iterable:D \iterable) {
Concurrent::Iterator.new(iterable)
}
multi concurrent-iterator($other) {
concurrent-iterator($other.list)
}
sub concurrent-seq($target) is export(:proc) {
Seq.new(concurrent-iterator($target))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment