perl6如何获得诺言的特定身份? [英] perl6 how to get specific identity of promises?

查看:87
本文介绍了perl6如何获得诺言的特定身份?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试对在promise中运行的3个echo服务器进行编码,但是我想知道是哪个promise正在执行echo.有没有办法做到这一点?

I am trying to code 3 echo servers running in promises, but I want to know which promise is doing the echoing. Is there a way to do that?

no strict;

for 0 .. 2 -> $index {
    @result[$index] = start {
        $myID = $index; 
        say "======> $myID\n";

        my $rsSocket = IO::Socket::INET.new:
            localhost => 'localhost',
            localport => 1234 + $index,
            listen    => 1;

        while $rsSocket.accept -> $rsConnection {
            say "Promise $myID accepted connection";
            while $rsConnection.recv -> $stuff {
                say "promise $myID Echoing $stuff";
                $rsConnection.print($stuff);
            }
            $rsConnection.close;
        }
    }
}

await @result;

回显服务器运行正常;经过"nc"测试;

The echo servers run ok; tested with "nc";

问题是创建承诺后,$myID变成了2,而我没有办法告诉哪个承诺正在执行当前回显.似乎所有承诺都使用了$myID.有没有一种方法可以创建特定于单个承诺的变量?

The problem is $myID becomes 2 after the promises are created, and there is no way for me to tell which promise is doing the current echoing. It seems that $myID is used by all the promises; is there a way to create variables that are specific to an individual promise?

推荐答案

您根本不需要一个$myID.您只能在Promise中使用$index,因为它已被限定为循环块.这是一个可行的修改(..严格要求):

You don't really need to have a $myID at all. You can just use $index in the promise because it has already been scoped to the loop block. Here's a working modification (..with strict on):

my @result = do for 0 .. 2 -> $index {
    start {
        say "======> $index\n";

        my $rsSocket = IO::Socket::INET.new:
            localhost => 'localhost',
            localport => 1234 + $index,
            listen    => 1;

        while $rsSocket.accept -> $rsConnection {
            say "Promise $index accepted connection";
            while $rsConnection.recv -> $stuff {
                say "promise $index Echoing $stuff";
                $rsConnection.print($stuff);
            }
            $rsConnection.close;
        }
    }
}

await @result;

照顾完这些后,我感到有必要指出,使用no strict似乎非常不必要.它不仅使您对诸如此类的奇怪范围问题持开放态度,而且在您的示例中,这样做基本上没有任何收获.

With that taken care of I feel the urge to point out that using no strict seems very unnecessary. Not only does it leave you open to weird scope issues like these, but you gain basically nothing from doing it in your example.

重新启用严格的未修改代码并修复两个编译错误显示仅总共节省了四次击键-牺牲了您在此处键入问题所用的许多键.

Re-enabling strict on your unmodified code and fixing the two compile errors shows have only saved a total of four keystrokes -- at the expense of however many keys you used typing up your question here.

这篇关于perl6如何获得诺言的特定身份?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆