0

我正在使用 Perl 5.10.1 中的线程进行一些测试,但我遇到了一些问题。首先,我有 2.6.32-5-amd64(64 位)的 Debian GNU/Linux 挤压/sid。

这是我的脚本

#!/usr/bin/perl -w
use strict;
use warnings;
use threads;  

sub threadProcess{
    my ($number, $counter) = @_; 
    print "Enter thread #" . $number . "\n";
    while($counter < 10){
        print "Thread #" . $number . ": " . $counter . "\n";
        $counter++;
    }
    print "Exit thread #" . $number . "\n";
}

sub main{ 
    my $counter = 0;

    my $thr1 = threads->create(\&threadProcess, 1, $counter);  
    my $thr2 = threads->create(\&threadProcess, 2, $counter); 

    my $res1 = $thr1->join();  
    my $res2 = $thr2->join(); 

    print "Bye...\n";
}

main(@ARGV);

这是输出:

Enter thread #1
Thread #1: 0
Thread #1: 1
Thread #1: 2
Thread #1: 3
Thread #1: 4
Thread #1: 5
Thread #1: 6
Thread #1: 7
Thread #1: 8
Thread #1: 9
Exit thread #1
Enter thread #2
Thread #2: 0
Thread #2: 1
Thread #2: 2
Thread #2: 3
Thread #2: 4
Thread #2: 5
Thread #2: 6
Thread #2: 7
Thread #2: 8
Thread #2: 9
Exit thread #2
Bye...

可能是什么问题?提前致谢!

4

1 回答 1

4

什么都没有,只是工作threadProcess太短了,以至于第一个线程可以在第二个线程初始化之前完成。

在你的循环中放一个延迟,你会看到线程同时工作。

while($counter < 10){
    print "Thread #" . $number . ": " . $counter . "\n";
    sleep 1;      # or Time::HiRes::sleep 0.25, etc.
    $counter++;
}
于 2012-05-01T16:12:10.430 回答