Perl6中是否有类似于Go goroutines的等效功能?

3
我可以看到。
perl6 -e '@r = do for ^500 {start { .say; sleep 3 }}; await @r'

我在我的系统上使用了大约十几个moar线程,并将它们用作承诺的池,但是我想像Go一样同时启动它们。这可能吗?


1
ThreadPoolScheduler 从 16 个最大线程开始,我相信你需要更改它。 - Brad Gilbert
1个回答

6
据我所知,goroutine 是一种非常底层的结构。
Perl 中的大多数内容都不是非常底层的。
你想要的最接近的可能是直接使用 Threads
my @r = do for ^100 { # currently aborts if it's much over 100
  Thread.start: { .say; sleep 3 };
}

# The implementation may actually create several threads
# for this construct
@r>>.finish;

我强烈建议你不要这样做,因为它不太可组合。


如果你想在等待3秒后打印数字,我会使用Promise.in方法,它返回一个Promise,在那么多秒后将被保持。
这个例子似乎同时创建了500个线程,但实际上可能没有启动任何额外的线程。
my @r = (^500).map: {
  Promise.in(3).then: -> $ { .say }
}
await @r;

Perl 6 还有 SuppliesChannels
# get three events fired each second
my $supply = Supply.interval: 1/3;

react {
  # not guaranteed to run in order.
  whenever $supply.grep(* %% 3) { print 'Fizz' }
  whenever $supply.grep(* %% 5) { print 'Buzz' }

  whenever $supply {
    sleep 1/10; # fudge the timing a little
    .put
  }

  whenever Promise.in(10) {
    say 'ten seconds have elapsed';
    done
  }
}

一般来说,异步构造的设计是为了隐藏线程处理中的一些复杂问题。实际上,使用线程最简单的方法之一可能就是在 mapgrep 方法调用之前添加 hyperrace。请保留HTML标签。
my @r = (^50).hyper( :batch(5), :degree(10) ).map: { .say; sleep 1 }
# use `race` instead of `hyper` if you don't
# care about the order of @r

您IP地址为143.198.54.68,由于运营成本限制,当前对于免费用户的使用频率限制为每个IP每72小时10次对话,如需解除限制,请点击左下角设置图标按钮(手机用户先点击左上角菜单按钮)。 - mpapec

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接