gpt4 book ai didi

multithreading - Perl 在一个线程中死掉(并停止整个程序)

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

我有一个产生一组工作线程的 Perl 脚本。当其中一个线程遇到 fatal error 时,我希望整个脚本终止并打印一条错误消息。

问题是...当您在线程中使用 die 时,它​​只会终止当前线程并显示类似 Thread 42 terminated abnormally: blah blah blah... 的消息。脚本的其余部分将继续运行。

示例:

use strict;
use warnings;
use threads;

# Create threads
for my $i (1 .. 5) {
threads->create(\&do_something, $i);
}

# Wait for all threads to complete
$_->join() for threads->list();

sub do_something {
my $i = shift;
die "I'm died" if $i == 3;
}

输出:

Thread 3 terminated abnormally: I'm died at line 15



如何在线程中发生 fatal error 杀死整个脚本?

最佳答案

根据perldoc threads :

Calling exit EXPR inside a thread causes the whole application to terminate. Because of this, the use of exit() inside threaded code, or in modules that might be used in threaded applications, is strongly discouraged.

If exit() really is needed, then consider using the following:

threads->exit() if threads->can('exit');   # Thread friendly
exit(status);

关于multithreading - Perl 在一个线程中死掉(并停止整个程序),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33025510/

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