之前學perl時候的一些筆記。主要是perl來寫多線程的程序,整理一下 html
1 多線程
#!/bin/perl use threads; use threads::shared; # 涉及到一些進程間變量的共享,用這個模塊 my $process = 4; my $child_num = 0; print $threads::VERSION.chr(10); while (1) { if ($child_num < $process){ my $params = $child_num.':..........'; my $thr = threads->create(\&start_thread, $params); $child_num ++; } #foreach my $t(threads->list()){ foreach my $t(threads->list(threads::joinable)){ $t->join(); } # all tasks done and no running child, then exit if ($child_num==4){ exit; } } sub start_thread(){ # do actually task here my $param = shift; print $param.chr(10); }
2 less
my $maxchild=10; for($i=0;$i<=$maxchild-1;$i++) { my $child=fork(); if($child) { # child >; 0, so we're the parent warn "launching child $child\n"; }else{ do_child($i); # child handles exit 0; # child is done } } exit; sub do_child { my $child_number=shift(@_); print("child ,$child_number \n"); }3
use Thread; #use threads::shared; my @threads; open(MHO,$mhofile); my @mholist=<MHO>; foreach my $mho (@mholist) { next unless defined $mho; print "start one thread"; $threads[$tempcount]=Thread->new(\&start_thread,$mho); $tempcount++; } foreach my $thread (@threads) { $thread->join(); } sub start_thread{ my ($infomho)=@_; print "in thread $infomho"; sleep 20; }
4 函數
#!/bin/perl use strict; use threads; use Cwd; use POSIX qw(strftime); ################################################################################ # 函數名: count # 函數描述: 數數 # 輸入: name 隨意輸入一個名字 # 輸出: 無 # 調用: # 被調用: # 返回: ################################################################################ sub count { my ($name) = @_; my $current_time = strftime "%Y-%m-%d %H:%M:%S", localtime; for ($i = 0; $i <= 10000; $i++) { print "$current_time $name $i"; } } 建立第一批線程 my $thread_1_01 = threads->create('count', Thread_1); my $thread_1_02 = threads->create('count', Thread_2); my $thread_1_03 = threads->create('count', Thread_3); my $thread_1_04 = threads->create('count', Thread_4); # 等待第一批線程結束完成 $thread_1_01->join(); $thread_1_02->join(); $thread_1_03->join(); $thread_1_04->join(); # 建立第二批線程 my $thread_2_01 = threads->create('count', Thread_5); my $thread_2_02 = threads->create('count', Thread_6); my $thread_2_03 = threads->create('count', Thread_7); # 等待第二批線程結束完成 $thread_2_01->join(); $thread_2_02->join(); $thread_2_03->join();
參考文檔: spa
http://www.cnblogs.com/joechen/archive/2009/04/27/1444569.html 線程
http://www.cnblogs.com/joechen/archive/2009/04/27/1444602.html 3d
5 perl語言last和next命令 code
#last 退出循環陳述 for($i=1;$i<=10;$i++) { last if ($i==5); #若是$i等於5的話就退出for循環 print"$i\n"; } #會把1到4之間的數值顯示出來. #next 到循環的下一個陳述 for($i<=10;$i++) { #若是是2的倍數的話,就到循環的下一個陳述 next if($i%2)==0) print"$i是一個奇數!\n"; } #會把1以10之間的奇數顯示出來。
參考文檔:http://hi.baidu.com/619195553dream/item/6ac361a8d4c137921510739f htm
總結一下,這個博客是之前作一個perl多線程時候積累的一些博客。收藏一下。^_^ blog