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

I'm experimenting with Perl and Threads at the moment and wondering if it is possible to do the following. I have the following code, what I want to know is how to make it so that when sub1 changes the $status to 0's, how can I make sub2 also register the variable's value change. Is this possible with threads? Is there another method I could use that would allow two while-loops running, while being able to change each others variable values?
use strict; use Thread; my $thr1; my $thr2; my $status = "1111"; print "Started\n"; $thr1 = new Thread \&sub1; $thr2 = new Thread \&sub2; sub sub2 { while (1) { print $status; } } sub sub1 { while (1) { $status = "0000"; print $status; } } $thr1->join; $thr2->join;

Replies are listed 'Best First'.
Re: Beginner: Threads and Variables
by IlyaM (Parson) on Nov 14, 2002 at 10:10 UTC
    I haven't used threads in Perl yet so I can be wrong but I think you have to declare variable as shared:
    use threads::shared; my $status : shared;
    See 'perldoc threads::shared' for details.

    --
    Ilya Martynov, ilya@iponweb.net
    CTO IPonWEB (UK) Ltd
    Quality Perl Programming and Unix Support UK managed @ offshore prices - http://www.iponweb.net
    Personal website - http://martynov.org

Re: Beginner: Threads and Variables
by broquaint (Abbot) on Nov 14, 2002 at 12:16 UTC
    Something like this perhaps
    use strict; use threads; use threads::shared; print "Started\n"; my $status : shared = 0; my $thr1 = threads->new( sub { sleep(1) and print "thread1: $status\n" while 1; } ); my $thr2 = threads->new( sub { sleep(1) and print "thread2: status incremented\n" while ++$status; } ); $thr1->join; $thr2->join; __output__ Started thread1: 1 thread2: status incremented thread1: 2 thread2: status incremented thread1: 3 thread2: status incremented thread1: 4 ...
    This requires perl5.8.0 compiled with threading, or with a slight modification, perl5+ without threading and using the inspired forks module.
    HTH

    _________
    broquaint

    update: fixed forks link per RMGir's node

      the inspired forks module

      Unfortunately, search.cpan.org has issues. Your link takes me to Net::Server::PreForkSimple rather than Elizabeth Mattijsen's forks module.

      You're right, though, that's one cool module.
      --
      Mike