Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much

Re: Updating global variable in multi-threaded program

by BrowserUk (Patriarch)
on Jan 29, 2014 at 12:04 UTC ( #1072496=note: print w/replies, xml ) Need Help??

in reply to Updating global variable in multi-threaded program

How to share the data across threads so that the value get updated properly.

Mark the shared variables as shared. See threads::shared.

Without any testing, something like:

use strict; use warnings; use threads; use threads::shared; my $currentWrite :shared = 10; my $totalSize = 1000; sub Progress { my $size = shift; $currentWrite += $size; my $currentProgress = $currentWrite / 100; print "Done ", $currentProgress, " of ", $totalSize, "\n"; } sub test { my $countRef = shift; my $count = $$countRef; Progress ( 11); print "Current count is $count\n"; } Progress(10); my $numThreads = 5; my @arrThreads; for my $i ( 1 .. $numThreads) { my $t = threads->create( \&test, \$i); push( @arrThreads, $t); } foreach (@arrThreads) { my $num = $_->join; }

With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
"Science is about questioning the status quo. Questioning authority".
In the absence of evidence, opinion is indistinguishable from prejudice.

Log In?

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

How do I use this?Last hourOther CB clients
Other Users?
Others exploiting the Monastery: (6)
As of 2023-12-05 01:42 GMT
Find Nodes?
    Voting Booth?
    What's your preferred 'use VERSION' for new CPAN modules in 2023?

    Results (25 votes). Check out past polls.