gpt4 book ai didi

multithreading - 我如何终止 Perl 线程?

转载 作者:行者123 更新时间:2023-12-02 08:44:11 27 4
gpt4 key购买 nike

在这个程序中,我创建了一个分支,然后从中调用 domultithreading。然后它创建几个线程。

sub domultithreading {
#Not my function
my ($num) = @_;
my @thrs;
my $i = 0;
my $connectionsperthread = 50;
while ( $i < $num ) {
$thrs[$i] = threads->create( \&doconnections, $connectionsperthread, 1 );
$i += $connectionsperthread;
}
my @threadslist = threads->list();
while ( $#threadslist > 0 ) {
$failed = 0;
}
}

sub kill {
#how can I kill the threads made in domultithreading?
kill 9, $pid;
print "\nkilling $pid\n";
}

然后我希望能够终止 fork 及其线程,但我无法弄清楚。有什么建议吗?

非常感谢

最佳答案

Perl 提供了两种并发模型:进程和线程。虽然你不应该无缘无故地混合这两者,但线程对进程的建模非常接近,所以我们几乎可以这样对待它们。具体来说,我们可以向线程发送信号。

进程可以用kill函数发出信号:kill SIGNAL => $pid,而线程可以用发出信号杀死 方法:$thr->kill(SIGNAL)。该方法返回线程对象。在 %SIG 散列中设置信号处理程序时可以拦截信号。

这意味着每个进程 TERM 信号处理程序 TERM 的所有子线程都像

 $_->kill(9)->join() for threads->list;

并且每个线程 TERM 信号处理程序只是简单地退出线程,或者进行清理:

 threads->exit; # exit the current thread

关于multithreading - 我如何终止 Perl 线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13708864/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com