如何让所有的 fork(ing) 子进程同时执行?
我有一个进程,我希望主线程运行一个循环并生成 n 个子线程,所有子线程都应休眠 j 秒,然后(或多或少)同时醒来并执行其操作。
我的代码看起来像这样 [根据 Dre 的请求编辑]:
#THE IDEA HERE IS SOMETIMES I WANT TO HOLD THE
SMS DELIVERY FOR $smsDelay number of seconds
if($smsDelay){
my $forkPid = fork();
if($forkPid){
next;
}
elsif($forkPid == 0){
#db connection disappears while children wait, so, need to reconnect (probably not the best way to handle THIS either! :)
$myDbC = DBI->connect([DBLOGIN STUFF]) or myDie("can not connect to db");
&logData("WAITING $smsDelay SECONDS TO SEND SMS");
sleep($smsDelay * 1);
$t = time();
print "sending SMS";
&send_sms_message($userPN, $smsText , $smsCampaignId);
print "SMS sent";
my $smsVerification = &getDeliveryStatus($userPN, '.smslog');
&logData("SMS delivery for $userPN, filename:$filename. Status = $smsVerification");
#save mms, sms, response code in db
&runSQL([SQL HERE]);
exit; #this should only exit the fork, not the entire process!
}
}else{
#HERE I WOULD SEND SMS IMMEDIATELY WITHOUT DELAY
}
我看到的是每个子进程都连续执行,但每个子进程在下一个子进程之间等待 j 秒!这不是我想要的(坦率地说,完全令人困惑)。我做错了什么?
TIA
I have a process where I want the main thread to run through a loop and produce n number of children, all of which should sleep for j seconds and then (more or less) simultaneously wake up and do their thing.
My code looks like this [Edited as per Dre's request]:
#THE IDEA HERE IS SOMETIMES I WANT TO HOLD THE
SMS DELIVERY FOR $smsDelay number of seconds
if($smsDelay){
my $forkPid = fork();
if($forkPid){
next;
}
elsif($forkPid == 0){
#db connection disappears while children wait, so, need to reconnect (probably not the best way to handle THIS either! :)
$myDbC = DBI->connect([DBLOGIN STUFF]) or myDie("can not connect to db");
&logData("WAITING $smsDelay SECONDS TO SEND SMS");
sleep($smsDelay * 1);
$t = time();
print "sending SMS";
&send_sms_message($userPN, $smsText , $smsCampaignId);
print "SMS sent";
my $smsVerification = &getDeliveryStatus($userPN, '.smslog');
&logData("SMS delivery for $userPN, filename:$filename. Status = $smsVerification");
#save mms, sms, response code in db
&runSQL([SQL HERE]);
exit; #this should only exit the fork, not the entire process!
}
}else{
#HERE I WOULD SEND SMS IMMEDIATELY WITHOUT DELAY
}
What I'm seeing is that each child is executed in succession, but each one waits j seconds IN BETWEEN the next! This is not what I'm after (and frankly totally confusing). What am I doing wrong?
TIA
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
他们应该同时醒来,我测试时他们也这样做了。我的代码:
Unix:
Windows (fork emulation):
我怀疑问题出在你没有显示的代码中。
They should simultaneously wake up, and they do when I tested. My code:
Unix:
Windows (fork emulation):
I suspect the problem is in the code you didn't show.