在
print-columns
中,仅保护写访问是否足够?还是必须保护读访问?#!/usr/bin/env raku
my @w_list_items;
len_items_list( <car tree house mouse dog mountain snow roof> );
@w_list_items.say;
sub len_items_list ( @list ) {
my Int $threads = Kernel.cpu-cores;
while $threads > @list.elems {
last if $threads < 2;
$threads = $threads div 2;
}
my Int $size = @list.elems div $threads;
my Array @portions = ( ^$threads ).map: { [ $size * $_, $size * ( $_ + 1 ) ] };
@portions[*-1][1] = @list.elems;
my Promise @promise;
for @portions -> $range {
my Int %cache;
@promise.push: start {
do for $range[0] ..^ $range[1] -> $i {
my $len = print-columns( @list[$i], %cache );
$i, $len;
}
};
}
@w_list_items = ();
for await @promise -> @portion {
for @portion {
@w_list_items[.[0]] := .[1];
}
}
}
sub print-columns( $str, %cache? ) returns Int {
my Int $width = 0;
for $str.Str.NFC {
if %cache.EXISTS-KEY( $_ ) {
$width = $width + %cache.AT-KEY( $_ );
}
else {
$width = $width + %cache.BIND-KEY( $_, char_width( $_ ) );
}
}
$width;
}
sub char_width ( $cp ) {
# dummy code:
return 1;
}
hyper
参数,这些参数正是与列表一起使用的。但第三个也是最重要的,最好不要在线程之间共享任何类型的东西;您正在共享%cache
。如果需要共享信息,则最好设置通道,并通过无状态函数进行并行工作。 - jjmerelo