我有這樣的測試腳本:使用線程到Perl的面向對象的封裝
use threads;
start();
sub start {
my $A = threads->create(\&A);
my $B = threads->create(\&B);
sleep;
}
sub A {
while (1) {
print "A\n";
sleep(1);
}
}
sub B {
while (1) {
print "B\n";
sleep(1);
}
}
這個輸出是(每秒一次,永遠):
A
B
我試圖做
package Test;
use threads;
sub new { my ($class) = @_;
my $self = {
A => undef,
B => undef
};
bless $self, $class;
return $self;
}
sub start { my ($self) = @_;
$self->{A} = threads->create(\&{$self->A});
$self->{B} = threads->create(\&{$self->B});
sleep;
}
sub A { my ($self) = @_;
while (1) {
print "A\n";
sleep(1);
}
}
sub B { my ($self) = @_;
while (1) {
print "B\n";
sleep(1);
}
}
1;
然後:
與面向對象的包相同的use Test;
my $test = Test->new();
$test->start();
這個輸出是(每秒一次,永遠):
A
好像代碼卡的第一個線程上。我很難理解Perl中線程背後的邏輯。如何從面向對象包中的第一個腳本複製相同的行爲?
第一個例子中的'start'例程應該在每個線程上使用invoke'join'而不是永久休眠。 –
我同意。我用'sleep',因爲我不得不輸入= P – calvillo