我是Perl的新手并尝试多线程。我从数据库中提取数据并在这些输出上运行我的代码。我确实得到了输出,但过了一会儿,它只是停止执行,我得到错误。是因为我用过叉子吗?我不确定......请帮忙。这是我的代码。
use strict;
use DBI;
#db variables have been declared already
my $dbh = DBI->connect("DBI:mysql:$database;host=$host", $user, $pw);
my $sql = qq{
SELECT......
};
my $sth = $dbh->prepare($sql);
$sth->execute();
my $child1 = 1;
my @threadsArray = ();
while(my @request = $sth->fetchrow_array()){
my $net = @request[0];
my $pid = fork();
if ($pid == -1) {
errorUsageMsg("Failed: Fork error.\n");
die;
} elsif ($pid == 0) {
exit(findPro($net,$child1));
}
else {
$child1++;
}
}
$sth->finish();
$dbh->disconnect;
if(my $pid > 0)
{#this is to avoid zombie process
while ( wait() != -1) { my $r = $? >> 8;
}
}
sub findPro
{
my $net= shift;
my $child_id = shift;
#in this portion, I have the code which calls an in-built function of an API say, func.
# created a session here to connect to the API say with my $session;
#calling the object which contains the in-built function, func say like...
my in-built = $session->get(.....);
my $obj = $in-built[0];
#after getting the result from that object, in the below line, I call func as shown.
my $result = $obj->func();
print $result;
while ( wait() != -1)
{
my $r = $? >> 8;
}
}
我得到了一些数据的输出,而对于其他数据,执行速度变慢,我得到错误,说不能调用方法" func"在未定义的值上。