多进程多线程模式下,主进程如何感知子进程或子线程的执行情况
编程中,主进程开始执行,之后产生一些子进程或者子线程执行任务,也就是Boss-Worker的模式,主进程和子进程或子线程并行执行。某些时间,主进程想知道子进程或子线程执行完了没有。请问在perl中该如何实现这个功能?多谢
作者: sclouder 发布时间: 2011-05-18
自己看了看文档,实现了一个子线程运行完成之后,主进程让子线程退出的方法,示例代码如下:
threads->create(\&run_thread);
threads->create(\&run_thread_15);
while(1) {
my @thrs = threads->list(threads::joinable);
foreach (@thrs) {
$_->join;
print "success join\n";
}
foreach (threads->list) {
print "threads now:", $_, "\n";
}
print "one round end\n";
sleep 5;
}
sub run_thread {
print "thread id is ", threads->tid(), "\n";
sleep 30;
}
sub run_thread_15 {
print "thread id is ", threads->tid(), "\n";
sleep 15;
}
其中关键的一个方法是 threads->list(threads::joinable),可以参见官方文档http://perldoc.perl.org/threads.html
threads->create(\&run_thread);
threads->create(\&run_thread_15);
while(1) {
my @thrs = threads->list(threads::joinable);
foreach (@thrs) {
$_->join;
print "success join\n";
}
foreach (threads->list) {
print "threads now:", $_, "\n";
}
print "one round end\n";
sleep 5;
}
sub run_thread {
print "thread id is ", threads->tid(), "\n";
sleep 30;
}
sub run_thread_15 {
print "thread id is ", threads->tid(), "\n";
sleep 15;
}
其中关键的一个方法是 threads->list(threads::joinable),可以参见官方文档http://perldoc.perl.org/threads.html
作者: sclouder 发布时间: 2011-05-18