Click here to get back home

global variables in threaded perl programs

 HomeNewsGroups | Search | About
 comp.lang.perl.misc    Post an article   get this group's latest topics as an RSS feed add this group's latest topics to your My MSN content add this group's latest topics to your My Yahoo content
Subject Author Date
global variables in threaded perl programs iloveperl 04-12-2008
Posted by iloveperl on April 12, 2008, 8:23 pm
Please log in for more thread options
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


Posted by Joost Diepenmaat on April 12, 2008, 8:28 pm
Please log in for more thread options
iloveperl@abc.com writes:

> 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

--
Joost Diepenmaat | blog: http://joost.zeekat.nl/ | work: http://zeekat.nl/

Similar ThreadsPosted
local variables and global variables June 27, 2006, 8:31 am
global variables in oop September 14, 2005, 6:01 pm
global variables February 18, 2007, 7:35 pm
How do I use global variables safely? August 13, 2005, 12:34 pm
global variables in a web service June 28, 2006, 6:44 pm
Modules, global variables and such February 10, 2008, 6:24 am
Global variables from a module, while using strict June 30, 2005, 5:58 pm
mod_perl and global variables during startup July 12, 2005, 1:53 am
Book: Higher-Order Perl: Transforming Programs with Programs July 9, 2005, 5:11 pm
Re: Book: Higher-Order Perl: Transforming Programs with Programs July 9, 2005, 11:10 pm

Our other projects:

Art Dolls, Fairies and Mermaids - Sunnyfaces.net

Roy's Linux, Programming and Search Engines messages

1-Script XML SitemapXML Sitemap