You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Raku的race并行循环中正确使用gather/take

在Raku并行循环中实现类似gather/take的结果收集

你遇到的问题根源在于:gather的上下文是线程局部的,race/hyper启动的并行线程无法共享外层gather的上下文,导致take报错;而第二种写法里race gather ...实际是先同步遍历序列,再对结果做并行处理,完全没达到循环体并行的目的。

下面是两种可行的解决方案:

方案1:使用Channel传递结果

Channel是Raku中用于线程间通信的工具,适合在并行任务中收集结果:

my $result-channel = Channel.new;

# 并行执行循环,将结果发送到通道
race for (^8).race(batch => 1, degree => 4) {
    sleep rand;
    $result-channel.send($_);
}

# 关闭通道,表明不会再发送数据
$result-channel.close;

# 收集通道中的所有结果
my @collected = $result-channel.list;
@collected.say;

执行后会得到随机顺序的结果,符合并行执行的预期。

方案2:使用hyper/map组合

如果不需要显式的循环,用hyper结合map也能实现并行处理并收集结果:

my @collected = (^8).hyper(batch => 1, degree => 4).map({
    sleep rand;
    $_
}).list;
@collected.say;

hyper将序列转为并行处理的HyperSeq,map在并行线程中执行逻辑,最后list收集所有结果,同样会得到随机顺序的输出。


内容的提问来源于stack exchange,提问作者Pawel Pabian bbkr

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 15:22:34