global variables in threaded perl programs

I

iloveperl

Hi,

I am thinking of writing a new script as a multi threaded
program. This is my first threaded program.
I wrote a small program to understand how
to share global variables in all threads.

use warnings;
use strict ;
use threads ;
use vars qw($sub1 $sub2) ;
$sub1 = 0 ;
$sub2 = 0 ;
my $thr1 = threads->new(\&sub1);
my $thr2 = threads->new(\&sub2);
sleep(10);
print "current $sub1 $sub2..\n" ;
sub sub1() {
$sub1 = 1000 ;
print "$sub1\n" ;
}
sub sub2() {
$sub2 = 2000 ;
print "$sub2\n" ;
}


In the above code it starts two threads in which global variables are
set to a value.
output of the program

1000
2000
current 0 0..

why does the last print line does not take the value of 1000 or 2000.

thanks.

print "current $sub1 $sub2..\n" ;
it does not print 1000 and 2000. rather it
 
J

Joost Diepenmaat

In the above code it starts two threads in which global variables are
set to a value.
output of the program

1000
2000
current 0 0..

why does the last print line does not take the value of 1000 or 2000.

Because no variables are shared by default. See perldoc threads::shared
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top