Perl如何加入所有线程
发布时间:2020-12-16 06:15:54 所属栏目:大数据 来源:网络整理
导读:我的代码如下: use threads;use threads::shared;use Thread::Queue;my $q = Thread::Queue-new();my @threads = ();my $run :shared = 1;$SIG{'TERM'} = sub { $run = 0; $q-enqueue('exit'); foreach(@threads){ $_-join(); }};push @threads,threads-cre
我的代码如下:
use threads; use threads::shared; use Thread::Queue; my $q = Thread::Queue->new(); my @threads = (); my $run :shared = 1; $SIG{'TERM'} = sub { $run = 0; $q->enqueue('exit'); foreach(@threads){ $_->join(); } }; push @threads,threads->create(proc1); push @threads,threads->create(proc2); sub proc1 { while($p = $q->dequeue()){ if($p eq 'exit'){ last; } ..... } $q->end(); threads->exit(); } sub proc2 { while($run){ ..... } } 在TERM信号我试图等待所有线程结束.但是,每当我通过TERM信号时,我的程序都会因错误而终止 Segmentation fault 如何解决这个问题? 解决方法
假设线程 – > create(proc1)甚至可以正常工作(这只是因为你没有使用use strict;你应该这样做),那么你的程序在创建线程后立即退出.您需要让主线程等待子线程完成.
修复该问题(并应用一些简化)会导致以下结果: use strict; use warnings; use threads; use threads::shared; use Thread::Queue 3.01 qw( ); my $q = Thread::Queue->new(); my $run :shared = 1; $SIG{TERM} = sub { print("Received SIGTERM. Shutting down...n"); $run = 0; $q->end(); }; print("$$n"); threads->create(&;proc1); threads->create(&;proc2); $_->join() for threads->list(); sub proc1 { while(my $p = $q->dequeue()) { sleep 1; # Placeholder } } sub proc2 { while($run){ sleep 1; # Placeholder } } 我没有得到段错误,但程序也没有退出.简单地不调用信号处理程序.这是因为Perl在调用信号处理程序之前正在等待join返回.您可以通过轮询可连接线程列表来解决这个问题.换句话说,替换 $_->join() for threads->list(); 同 my $running_threads = 2; while ($running_threads) { for my $thread (threads->list(threads::joinable)) { $thread->join(); $running_threads--; } sleep 1; } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
推荐文章
站长推荐
- inno-setup – 如何将参数传递给Inno Setup命令行
- ThinkPHP实现分页功能
- 为什么我的Perl程序抱怨“无法在@INC中找到URI.p
- Delphi的idhttp报IOHandler value is not valid错
- PHP Laravel 6.2 中用于用户登录的新密码确认流程
- Lua病理模式是否具有指数运行时间?
- perl – List :: MoreUtils mesh或’zip’功能
- Django——模板层(template)(模板语法、自定义模
- 数组 – RTTI动态数组TValue Delphi 2010
- perl – Term :: Readline:encoding-question
热点阅读