Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

Re: Using threads::shared with multidimensional arrays

by BrowserUk (Patriarch)
on Jun 10, 2006 at 23:18 UTC ( [id://554642]=note: print w/replies, xml ) Need Help??


in reply to Using threads::shared with multidimensional arrays

Silly example. The background thread randomly increments values in the shared array of shared arrays, whilst the foregorund thread displays it.

Things to note.

  1. To build a shared multi-dimensional array, you have to share the base array, and then fill it with references to shared arrays.
  2. You must share the arrays before you put anything in them. Calling share() discards any existing contents of an array (or hash).
  3. To share an anonymous array (or hash), you have to bypass the prototype on share() by calling it with &.
  4. 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.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://554642]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others goofing around in the Monastery: (5)
As of 2024-04-23 21:24 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found