在Perl6中是否有等同于Go goroutines?

问题描述 投票:3回答:1

我可以看到

perl6 -e '@r = do for ^500 {start { .say; sleep 3 }}; await @r'

在我的系统上制作了大约12个moar线程,并将它们用作承诺的池,但是我想像在Go中一样一次启动它们。有可能吗?

go perl6 raku
1个回答
5
投票

据我了解,goroutines是一个非常底层的构造。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秒钟后打印出数字,我会使用.inPromise方法,该方法将返回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
  }
}

通常,异步构造的设计是为了隐藏一些必须由线程处理的较琐碎的事情。

实际上,最简单的使用线程的方法之一可能就是在hyperhyper方法调用之前添加racerace

map
© www.soinside.com 2019 - 2024. All rights reserved.