在Perl6中是否有与Go goroutines相同的功能?

Сух*_*й27 3 go perl6

我知道

perl6 -e '@r = do for ^500 {start { .say; sleep 3 }}; await @r'
Run Code Online (Sandbox Code Playgroud)

moar在我的系统上创建了大约十几个线程并将它们用作承诺池,但我想像Go一样立即启动它们.那可能吗?

Bra*_*ert 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;
Run Code Online (Sandbox Code Playgroud)

我强烈建议你不要这样做,因为它不是很容易组合.


如果您想在等待3秒后打印出数字,我会使用Promise.in方法返回一个Promise,它将在很多秒内保留. 此示例似乎几乎同时创建500个线程,但实际上可能不会启动任何其他线程.

my @r = (^500).map: {
  Promise.in(3).then: -> $ { .say }
}
await @r;
Run Code Online (Sandbox Code Playgroud)

Perl 6还有供应渠道

# 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
  }
}
Run Code Online (Sandbox Code Playgroud)

一般来说,异步结构的设计可以隐藏一些你必须用线程处理的毛茸茸的东西.

实际上,使用线程的最简单方法之一可能是在调用或方法调用之前hyperrace之前:mapgrep

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
Run Code Online (Sandbox Code Playgroud)