Fer*_*ata 8 concurrency perl6 promise
我写了这个测试程序:
await Promise.anyof(
Promise.allof((^5).map: {start { sleep 10; say "done $_" } }),
Promise.in(5).then: { say 'ouch' }
);
sleep 10;
Run Code Online (Sandbox Code Playgroud)
当第二个承诺超时时,它打印'ouch'并等待退出,但第一个promise的代码块仍在运行.五秒钟之后,它的五个过程结束并打印"完成":
$ ./test1.p6
ouch
done 0
done 1
done 2
done 3
done 4
Run Code Online (Sandbox Code Playgroud)
我试图终止第一个承诺,将其分配给变量,然后.break从第二个承诺调用该方法,但它不起作用.
有没有办法杀死第一个承诺和其他五个承诺呢?
你必须以某种方式告诉过程它不必完成.
my $cancel = Cancellation.new;
await Promise.anyof(
Promise.allof(
(^5).map: {
last if $cancel.cancelled;
start {
sleep 10;
say "done $_" unless $cancel.cancelled
}
}
),
Promise.in(5).then: {
$cancel.cancel;
say 'ouch'
}
);
Run Code Online (Sandbox Code Playgroud)
如果你想要Promise.in()取消这样的东西,让我们先看看现有的代码.
method in(Promise:U: $seconds, :$scheduler = $*SCHEDULER) {
my $p := self.new(:$scheduler);
my $vow := $p.vow;
$scheduler.cue({ $vow.keep(True) }, :in($seconds));
$p
}
Run Code Online (Sandbox Code Playgroud)
请注意,结果$scheduler.cue是取消.
我只是为了简单而包装一个Promise和一个类中的Cancellation.
(我不想重新实现每一种方法).
class Cancellable-Timer {
has Promise $.Promise;
has $!vow;
has Cancellation $!cancel;
method !SET-SELF ( $!promise, $!vow, $!cancel ){
self
}
method in (::?CLASS:U: $seconds, :$scheduler = $*SCHEDULER) {
my $p := Promise.new(:$scheduler);
my $vow := $p.vow;
my $cancel = $scheduler.cue({ $vow.keep(True) }, :in($seconds));
self.bless!SET-SELF($p,$vow,$cancel);
}
method cancel ( --> Nil ) {
# potential concurrency problem
if $!Promise.status == Planned {
$!cancel.cancel; # cancel the timer
$!vow.break("cancelled"); # break the Promise
}
}
method cancelled () {
# Ignore any concurrency problems by using the Promise
# as the sole source of truth.
$!Promise.status ~~ PromiseStatus::Broken
}
}
my $timer = Cancellable-Timer.in(1);
my $say = $timer.Promise.then: *.say;
Promise.in(0.1).then: {$timer.cancel};
await $say;
Run Code Online (Sandbox Code Playgroud)
请注意,上面的课程只是粗略的初稿.