dongshi2458 2015-08-10 18:59
浏览 16
已采纳

在Perl6中有与Go goroutines等效的东西吗?

I can see that

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

makes about a dozen of moar threads on my system and use them as pool for promises, but I would like to start them all at once like in Go. Is that possible?

  • 写回答

1条回答 默认 最新

  • doulianxi0587 2015-08-11 01:51
    关注

    From what I understand goroutines are a very low level construct.
    Most things in Perl are not very low level.

    The closest to what you think you want is probably to directly use 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;
    

    I highly recommend you not do that though as it is not very composable.


    If you instead wanted to print out the numbers after waiting 3 seconds I would have used the .in method of Promise which returns a Promise that will be kept in that many seconds.
    This example appears to create 500 threads nearly simultaneously, but may not actually start any additional threads.

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

    Perl 6 also has Supplies and Channels

    # 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
      }
    }
    

    In general the design of asynchronous constructs are there to hide some of the hairier things you have to handle with threads.

    In fact one of the easiest ways to use threads may well be to just add hyper or race before a map or grep method call:

    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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大