LINUX.ORG.RU

Perl + threads


0

0

Подскажите, почему в следуюшем примере $data{$i} не изменяется? А если поменять $thr{$i} = threads->new(\&sub1, $i); на $thr{$i} = threads->new(\&sub1($i));

то $data{$i} изменяется но perl начинает ругаться:

thread failed to start: Not a CODE reference at thr.pl line 15.

>> thr.pl

#!/usr/bin/perl -w

use strict; use threads;

sub sub1;

my %thr; my %data;

foreach my $i (0..1) { $data{$i} = ""; $thr{$i} = threads->new(\&sub1, $i); $thr{$i}->join; }

foreach my $i (0..1) { print "$data{$i}\n"; }

exit;

sub sub1 { my $a = $_[0]; $data{$a} = "a $a";

async{ $data{$a} = "a $a"; sleep 3-$a; }; return 0; }


Подскажите, почему в следуюшем примере $data{$i} не изменяется?
А если поменять
$thr{$i} = threads->new(\&sub1, $i);
на
$thr{$i} = threads->new(\&sub1($i));

то $data{$i} изменяется но perl начинает ругаться:

thread failed to start: Not a CODE reference at thr.pl line 15.

>> thr.pl

#!/usr/bin/perl -w


use strict;
use threads;

sub sub1;

my %thr;
my %data;

foreach my $i (0..1)
{
$data{$i} = "";
$thr{$i} = threads->new(\&sub1, $i);
$thr{$i}->join;
}

foreach my $i (0..1)
{
print "$data{$i}\n";
}

exit;

sub sub1 {
my $a = $_[0];
$data{$a} = "a $a";

async{
$data{$a} = "a $a";
sleep 3-$a;
};
return 0;
}

DRuG
() автор топика

ССЗБ. Разумный человек НИКОГДА не будет использовать виндозную отрыжку - треды. Или fork, или КА на select.

anonymous
()

Перед тем как что-то писать было бы ещё здорово что-нибудь почитать...

`man perlthrtut`:

[-- CUT --]
       The biggest difference between Perl ithreads and the old 5.005 style
       threading, or for that matter, to most other threading systems out
       there, is that by default, no data is shared. When a new perl thread is
       created, all the data associated with the current thread is copied to
       the new thread, and is subsequently private to that new thread!  This
       is similar in feel to what happens when a UNIX process forks, except
       that in this case, the data is just copied to a different part of mem-
       ory within the same process rather than a real fork taking place.

       To make use of threading however, one usually wants the threads to
       share at least some data between themselves. This is done with the
       threads::shared module and the " : shared" attribute:

           use threads;
           use threads::shared;

           my $foo : shared = 1;
           my $bar = 1;
           threads->new(sub { $foo++; $bar++ })->join;

           print "$foo\n";  #prints 2 since $foo is shared
           print "$bar\n";  #prints 1 since $bar is not shared

[-- CUT --]

nblx
()
Вы не можете добавлять комментарии в эту тему. Тема перемещена в архив.