[Chicago-talk] A question on threading

me at heyjay.com me at heyjay.com
Sun Jun 6 10:43:15 CDT 2004


I got it to work.

#!/usr/bin/perl

package Reader;

use 5.008003;
use strict;
use warnings;

use base qw(Class::Accessor);
use threads;
use threads::shared;

__PACKAGE__->mk_accessors( qw/_run _thread/ );

sub start {

    my $self = shift;

    my $run = 1;
    $self->_run(share($run));

    my $t = threads->new(\&loop, $self);
    $self->_thread(share($t));
}

sub add {
    my $self = shift;
    ${$self->_run}++;
}

sub subt {
    my $self = shift;
    ${$self->_run} -= 1;
}

sub stop {
    my $self = shift;
    ${$self->_run} = 0;
    print "set flag: ", ${$self->_run}, " \n";
    my $t = $self->_thread;
    $t->join;
}

sub loop {

    my $self = shift;

    while (${$self->_run}) {
        print "running: ", ${$self->_run}, " \n";
        sleep 1;
    }

    print "running: ", ${$self->_run}, " \n";

}

package main;

my $reader = Reader->new();

$reader->start;
sleep 1;
$reader->add;
sleep 1;
$reader->add;
sleep 2;
$reader->add;
sleep 2;
$reader->subt;
sleep 2;
$reader->stop;
print "stopping\n";
print "done\n";

----- Original Message ----- 
From: <me at heyjay.com>
To: "chicago-pm" <chicago-talk at mail.pm.org>
Sent: Saturday, June 05, 2004 5:32 PM
Subject: [Chicago-talk] A question on threading


> Hi,
> 
> I'm getting unpredictable (at least to me) result.  
> If I run the code below, repeatedly, every so often I get:
> 
> [o10]:~> ./thread
> Invalid value for shared scalar at ./thread line 25.
> A thread exited while 2 threads were running.
> 
> the other times it works as expected.  I don't see what's
> wrong with the code
> 
> All I'm trying to do is start a new thread print out a shared value
> then stop the thread, and have it stop nicely.
> 
> I made an example that demonstrates the problem (should be 
> cut/paste runnable as is)
> 
> [o10]:~> cat ./thread
> 
> #!/usr/bin/perl
> 
> package Reader;
> 
> use 5.008003;
> use strict;
> use warnings;
> 
> use base qw(Class::Accessor);
> use threads;
> use threads::shared;
> 
> __PACKAGE__->mk_accessors( qw/_run _thread/ );
> 
> sub start {
> 
>     my $self = shift;
> 
>     my $run : shared = 1;
>     my $t : shared;
> 
>     $self->_run(\$run);
> 
>     my $sub = \&loop;
>     $t = threads->new($sub, $self);
>     $t->detach;
>     $self->_thread(\$t);
> }
> 
> sub stop {
>     my $self = shift;
>     ${$self->_run} = 0;
>     ${$self->_thread}->join;
> }
> 
> sub loop {
> 
>     my $self = shift;
> 
>     while (${$self->_run}) {
>         print "running: ", ${$self->_run}, " \n";
>     }
> }
> 
> package main;
> 
> my $reader = Reader->new();
> 
> $reader->start;
> $reader->stop;
> 
> _______________________________________________
> Chicago-talk mailing list
> Chicago-talk at mail.pm.org
> http://mail.pm.org/mailman/listinfo/chicago-talk
> 
> 



More information about the Chicago-talk mailing list