Perl多进程与多线程简单示例
发布时间:2020-12-16 00:20:13 所属栏目:大数据 来源:网络整理
导读:多进程: #!/usr/bin/perluse strict;use warnings;print "Starting main programn";my @childs;for ( my $count = 1; $count = 10; $count++) {my $pid = fork();if ($pid) {# parent#print "pid is $pid,parent $$n";push(@childs,$pid);} elsif ($pid =
多进程: #!/usr/bin/perl use strict; use warnings; print "Starting main programn"; my @childs; for ( my $count = 1; $count <= 10; $count++) { my $pid = fork(); if ($pid) { # parent #print "pid is $pid,parent $$n"; push(@childs,$pid); } elsif ($pid == 0) { # child sub1($count); exit 0; } else{ die "couldnt fork: $!n"; } } foreach (@childs) { my $tmp = waitpid($_,0); print "done with pid $tmpn"; } print "End of main programn"; sub sub1 { my $num = shift; print "started child process for $numn"; sleep $num; print "done with child process for $numn"; return $num; } 多线程: #!/usr/bin/perl use strict; use warnings; use threads; use threads::shared; print "Starting main programn"; my @threads; for ( my $count = 1; $count <= 10; $count++) { my $t = threads->new(&;sub1,$count,"hello,word"); push(@threads,$t); } foreach (@threads) { my $num = $_->join; print "done with $numn"; } print "End of main programn"; sub sub1 { my ($num,$str) = @_; print "started thread $num,$strn"; sleep $num; print "done with thread $numn"; return $num . " haha..."; } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |