dvinay has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks, Need an help here, i am using multi-threaded perl script, where i am calling an subroutine in which its accessing global variable defined in main function, now problem is that all threads are accessing this variable at same time, and i want this variable to be incremented each time this subrountine is called from main script, how can i do this below is the code for this
use threads; my @arr = (1,2,3,4); my $outnumber=1; print "\n variable outside thread that is in main program $outnumber\n +"; my @threads; foreach (@arr) { push @threads, threads->new(\&doSomething, $_, $outnumber); } foreach (@threads) { $_->join(); } sub doSomething () { my ($thread)=@_; lock $outnumber; my $intervariable=$outnumber; print "\n Before increment is $intervariable\n"; ++$intervariable; print "\n After increment is $intervariable\n"; print "thread $thread\n"; }

Replies are listed 'Best First'.
Re: Multi-threaded script
by roboticus (Chancellor) on Sep 13, 2013 at 05:05 UTC

    dvinay:

    If you'd look at the docs for threads, it would tell you the answer. You need to share your variable(s). For a description of how, see threads::shared.

    By the way, if you'd use code tags around your code, it would be easy to read your code.

    ...roboticus

    When your only tool is a hammer, all problems look like your thumb.

      Hi, You mean to say i need to make that global variable as shared , if yes let me know how to do it. your help is much appreciated. Thanks, Vinay