- #!/usr/bin/perl -w
- # 裝載perl線程模塊
- use threads;
- use POSIX qw(strftime);
- sub produce {
- my $thread_name = shift;
- while(1) {
- my $r = int(rand(100));
- # 獲得本線程內當前時間
- my $now_time = strftime "%Y-%m-%d %H:%M:%S", localtime;
- # 獲得本線程的ID
- $n = threads->tid();
- my $r2 = int(rand(3));
- printf("$thread_name \$random: %-2s | \$random2: $r2 | thread_id: $n | $now_time |\n",$r);
- sleep($r2);
- }
- }
- # 創建N個線程,每個線程調用 &produce 子例程,並傳送一個參數.
- my $jason1 = threads->create(\&produce, "jason1");
- my $jason2 = threads->create(\&produce, "jason2");
- my $jason3 = threads->create(\&produce, "jason3");
- my $jason4 = threads->create(\&produce, "jason4");
- my $jason5 = threads->create(\&produce, "jason5");
- # 線程結束,收割.
- $jason1->join();
- $jason2->join();
- $jason3->join();
- $jason4->join();
- $jason5->join();
use threads;模塊的詳細使用方法還要好好研究.
http://search.cpan.org/~jdhedden/threads-1.82/lib/threads.pm
注:
之前看了段時間的Thread模塊.後來才發現.這個模塊已經被放棄了.因爲有很多問題.
打算用perl寫多線程,還是好好研究threads.