React uses a single thread in channel processing

My intention is for different threads to be simultaneously read from the same channel and processed asynchronously. I thought it would be a trick:

my Channel $KXGA .= new; for ^100 { $KXGA.send( (100000..200000).pick ); } my $sums = start react whenever $KXGA -> $number { say "In thread ", $*THREAD.id; say "β†’ ", (^$number).sum; } 

(this freezes because I am not closing the channel, but please do not look at it). This outputs whatsoever I do:

 In thread 4 β†’ 6995966328 In thread 4 β†’ 12323793510 In thread 4 β†’ 5473561506 

Therefore, it always uses one thread and processes things sequentially, and not in parallel. Is there any way to do this? Even if I start thread in the whenever block, the result will be exactly the same ...

+5
source share
1 answer

The react / whenever designed to process one message at a time and in full. The fact is that the state held in the react block is safe because of this.

There may be several workers reading from Channel ; they just need to be configured as follows:

 my @sums; for ^4 { push @sums, start react whenever $KXGA -> $number { say "In thread ", $*THREAD.id; say "β†’ ", (^$number).sum; } } 

This react approach, when used with use v6.d.PREVIEW , has the advantage that, with less work, it will not actually occupy 4 threads, and they can continue to work with other pools. If instead the entire application simply processes the material from Channel , and that’s all, you will have less overhead and better locality with just:

 my @sums; for ^4 { push @sums, start for $KXGA.list -> $number { say "In thread ", $*THREAD.id; say "β†’ ", (^$number).sum; } } 

Unlike react there is no way to react to different data sources in this approach (the reason Channel works with react is primarily that you can consume them and work with asynchronous data sources at the same time, or possibly deal with multiple channels at the same time) . But if you don’t need it, then the for method is a bit simpler in the code and almost certainly faster (and, as in the case of react , the loops compete over the elements in the Channel and end gracefully when it is closed).

+8
source

Source: https://habr.com/ru/post/1276190/


All Articles