Silly example. The background thread randomly increments values in the shared array of shared arrays, whilst the foregorund thread displays it.
Things to note.
- To build a shared multi-dimensional array, you have to share the base array, and then fill it with references to shared arrays.
- You must share the arrays before you put anything in them. Calling share() discards any existing contents of an array (or hash).
- To share an anonymous array (or hash), you have to bypass the prototype on share() by calling it with &.
- I haven't used lock() in this example, but be aware that if you lock the base array each time, you will severally restrict the performance of both threads. Applying locking to the subarrays, or individual scalars as appropriate to your code, will decrease the contention and improve performance.
#! perl -slw
use strict;
use threads;
use threads::shared;
our $X :shared; $X ||= 10;
our $Y :shared; $Y ||= 10;
sub background {
my $AoA = shift;
while( 1 ) {
$AoA->[ rand $Y ][ rand $X ]++;
select undef, undef, undef, 0.01;
}
}
my $AoA: shared = &share( [] );
@{ $AoA } = map{ &share( [] ) } 1 .. $Y;
@{ $AoA->[ $_ ] } = (0) x $X for 0 .. $X-1;
async \&background, $AoA;
while( 1 ) {
system 'cls';
print "@$_" for @{ $AoA };
select undef, undef, undef, 0.1;
}
Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
Lingua non convalesco, consenesco et abolesco. -- Rule 1 has a caveat! -- Who broke the cabal?
"Science is about questioning the status quo. Questioning authority".
In the absence of evidence, opinion is indistinguishable from prejudice.