perl6 线程读取干扰

lis*_*tor 5 multithreading raku

我需要从同一个套接字或 $*IN 读取多个线程;然而,似乎有错误,因为每个人都试图从同一个来源读取(我认为)。解决此问题的最佳方法是什么?谢谢 !!

my $x = start { prompt("I am X: Enter x: "); }
my $y = start { prompt("I am Y: Enter y: "); }

await $x, $y;
say $x;
say $y;
Run Code Online (Sandbox Code Playgroud)

以下是错误:

I am X: Enter x: I am Y: Enter y: Tried to get the result of a broken Promise
  in block <unit> at zz.pl line 4

Original exception:
    Tried to read() from an IO handle outside its originating thread
      in block  at zz.pl line 1
Run Code Online (Sandbox Code Playgroud)

谢谢 !!

sml*_*mls 5

On the latest development snapshot of Rakudo, your code actually works without throwing any exception on my system...
However, it still immediately asks for both values (I am X: Enter x: I am Y: Enter y:).

To make the second prompt wait until the first one has completed, you could use a Lock:

#--- Main code ---

my $x = start { synchronized-prompt "I am X: Enter x: "; }
my $y = start { synchronized-prompt "I am Y: Enter y: "; }

await $x, $y;
say $x.result;
say $y.result;


#--- Helper routines ---

BEGIN my $prompt-lock = Lock.new;

sub synchronized-prompt ($message) {
    $prompt-lock.protect: { prompt $message; }
}
Run Code Online (Sandbox Code Playgroud)

棘手的部分是需要在线程开始并发使用它之前初始化锁。这就是为什么我在子程序Lock.new 之外,在synchronized-prompt程序的主线中调用的原因。我没有在程序的顶部执行此操作,而是使用BEGIN移相器,以便将其放置在子例程旁边。