global variables in threaded perl programs

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View

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);
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

current 0  0..

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


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

Re: global variables in threaded perl programs writes:

Quoted text here. Click to load it

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

Joost Diepenmaat | blog: | work: /

Site Timeline