On Fri, Feb 13, 2009 at 02:42, Kelvin Philip <kelvinphi...@gmail.com> wrote:
> Hi,
>
> I am calling two seperate fuctions defined under two different perl modules
> via two independent threads. Now, I use the $thr->join; command to wait for
> the first thread to complete and then start the second. But it seems that
> the two module functions are being executed simultaneously. The interpreter
> throws error saying that some variables which are used in the second
> function is uninitialised. Actually , those were defined in the first
> function. My code looks something like this:
>
> *use threads;*
> *use strict;*
> *use warnings;*
> *use module1;*
> *use module2;*
> **
> *my $thr1 = threads->new(\&func_module1);*
> *$thr1->join;*
> **
> *my $thr2 = threads->new(\&func_module2);*
> *$thr2->join;*
>
> Note: The func_module1 & func_module2 are subfunctions defined under moule1
> & module2 respectively.
>
> Please suggest a solution for this issue.
>
> Regards,
> Kelvin
>

Why are you using threads if you desire the code to run sequentially?
The only value threads add to a program is the ability to run
functions asynchronously.  And they add that functionality by
increasing the complexity drastically.

Also, why is a function in one module setting variables that are to be
accessed by another module?  This is a bad practice.  If the second
function needs state information from the first function then the
first function should return that information and you should then pass
that information to second function.  One reason (and it is not even
the most important of the reasons) is the one you have run into:
threads don't share variables by default.

from http://perldoc.perl.org/threads.html
       The threads API is loosely based on the old Thread.pm API. It is very
       important to note that variables are not shared between threads, all
       variables are per default thread local.  To use shared variables one
       must use threads::shared.

If you use threads::shared, you must ensure that two threads are not
trying to use the same variable at the same time (i.e. you must call
lock() on the variable before reading or changing it).  Locks are
tricky things and it is easy to get into a deadlock situation.  A
simple case of deadlock occurs when thread 1 wants $foo and has $bar
locked and thread 2 has $bar locked and wants $foo.  They both will
wait forever to get their locks.

-- 
Chas. Owens
wonkden.net
The most important skill a programmer can have is the ability to read.

-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to