2012-05-01 65 views
0

我正在使用Perl 5.10.1中的線程進行一些測試,但我遇到了一些問題。首先,我有2.6.32-5-amd64(64位)的Debian GNU/Linux squeeze/sid。帶腳本的Perl腳本逐步工作而不是異步腳本

這是我的腳本

#!/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... 

可能是什麼問題?提前致謝!

+0

嘗試1000次迭代。 – Mat

+0

謝謝哈哈哈我想念那部分,我的不好但謝謝! – pablomarti

回答

4

沒有什麼,除了threadProcess的作業太短以至於第二個線程可以初始化之前第一個線程可以完成。

延遲你的循環,你會看到線程在同一時間工作。

while($counter < 10){ 
    print "Thread #" . $number . ": " . $counter . "\n"; 
    sleep 1;  # or Time::HiRes::sleep 0.25, etc. 
    $counter++; 
} 
+0

謝謝!所以對不起,我忘了...謝謝! – pablomarti