gpt4 book ai didi

multithreading - Perl:从并行线程派生

转载 作者:行者123 更新时间:2023-12-03 13:15:13 24 4
gpt4 key购买 nike

下面的代码应该运行2个并行线程,每个线程执行fork(),等待子进程完成,然后线程应加入(完成)并打印结果。
实际上,第一个 fork 的子进程按预期完成,但是第二个 fork 卡在_mutex_lock()上试图退出,因此第二个线程永远不会加入,直到您用-9信号手动杀死第二个子进程为止。
有人可以解释为什么会发生这种情况,以及如何避免这种情况吗?

use strict;
use warnings;
use threads;
use Data::Dumper;

sub Run
{
my $tid = threads->tid();
my $log = {};
$log->{"[$$:$tid]:00"} = "started";
my $pid = fork();
if ($pid == 0)
{
print "In child ($$): started\n";
sleep 3;
print "In child ($$): finished\n";
# system("kill -9 $$"); -- brutal way
exit 0;
}
waitpid($pid, 0);
my $exitCode = $? >> 8;
$log->{"[$$:$tid]:01"} = "finished, code=$exitCode";
return $log;
}

my @threads = ();
foreach (1..2)
{
push @threads, threads->new(sub { return Run() });
}
print Dumper($_->join()) for @threads;

最佳答案

在我的Linux机器上,可以使用POSIX中的_exit代替exit。但是,此解决方案可能无法移植到其他平台。

链接的文档说:

Note that when using threads and in Linux this is not a good way to exit a thread because in Linux processes and threads are kind of the same thing (Note: while this is the situation in early 2003 there are projects under way to have threads with more POSIXly semantics in Linux). If you want not to return from a thread, detach the thread.



同样, perlthrtut - Tutorial on threads in Perl

Thinking of mixing fork() and threads? Please lie down and wait until the feeling passes. Be aware that the semantics of fork() vary between platforms. For example, some Unix systems copy all the current threads into the child process, while others only copy the thread that called fork(). You have been warned!

关于multithreading - Perl:从并行线程派生,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58381769/

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