#!/usr/bin/perl
#打印主线程PID
print "[1] Dad process PID is:".$$."\n";
#-申请一个子线程,产生进程号,
#-然后立即进入子线程,直到子线程退出,然后回到主线程。
#-该进程号,对子线程返回0,对主线程返回子线程的ID.
#(这一机制,方便判断当前处于哪个线程)
defined(my $child1_pid = fork) or die "Failed to fork:$!";
unless($child1_pid)#-子线程的特点是,进入子线程后马上挂到后台执行
{ #-然后去执行主线程
sleep(3);
print "[2] Child1_pid in child is:".$child1_pid."\n";
print "[3] Child1 process PID is:".$$."\n";
system('echo [4] hello world!');
exit(0);
}
print "[5] child1_pid in Dad is:".$child1_pid."\n";
defined(my $child2_pid = fork) or die "Failed to fork:$!";
unless($child2_pid)
{
sleep(4);
print "[6] Child2_pid in child is:".$child2_pid."\n";
print "[7] Child2 process PID is:".$$."\n";
system('echo [8] hello world!');
exit(0);
}
print "[9] child2_pid in Dad is:".$child2_pid."\n";
waitpid($child1_pid,0);#等待子线程执行完毕再退出主线程
waitpid($child2_pid,0);#等待子线程执行完毕再退出主线程
#你看到的打印信息顺序应该是:159(主) 234(子1) 678(子2) ,注意子线程里的延迟时间
【perl】多线程机制
于 2022-02-19 16:26:46 首次发布