Perl - 捕获意外终止

发布于 2024-10-21 12:07:43 字数 305 浏览 3 评论 0原文

我有一些代码可以一次生成 5 个线程。我分离这些线程,但有一个共享变量 $THREADCOUNT,我在线程调用调用的子过程开始时递增该变量,并在线程结束时递减。当 $THREADCOUNT 等于 0 时,我会再生成 5 次。

问题是,有时线程会意外退出,并且 $THREADCOUNT 永远不会使其变为 0,因此程序会停止。有没有办法捕获这样的退出并在意外退出时使用 $THREADCOUNT--

非常感谢。这是我的第一篇文章,如果有不清楚的地方,敬请谅解。

克里斯

I have some code that spawns 5 threads of itself, at a time. I detach those threads, but have a shared variable $THREADCOUNT that I increment at the beginning of the subprocedure that is called by the thread call, and decrement at the end of the thread. When $THREADCOUNT equals 0, I spawn another 5 times.

The problem is, sometimes the thread exits unexpectedly and the $THREADCOUNT never makes it to 0, so the program stops. Is there someway to capture an exit like this and have $THREADCOUNT-- on unexpected exit?

Thanks so much. This is my first post so appologies if it's a little unclear.

Chris

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

故人如初 2024-10-28 12:07:43

共享 $THREADCOUNT 变量真的有必要吗?调用threads->list(threads::running)将告诉您是否有任何spawn仍在运行。

Is the shared $THREADCOUNT variable really necessary? A call to threads->list(threads::running) will tell you whether any of your spawn are still running.

暮年慕年 2024-10-28 12:07:43

我不知道什么时候有人会想要使用detach。我会使用类似

use threads;

my %workers;

sub start_worker {
   my $thread = threads->create(@_);
   $workers{$thread->tid} = $thread;
   return $thread;
}

sub collect_finished_workers {
   for my $thread (threads->list(threads::joinable)) {
      $thread->join()
         if delete($workers{$threads->tid});  # Don't assume we own all threads.
   }
}

sub get_worker_count {
   collect_finished_workers();
   return 0+keys(%workers);
}

“请注意”的方法,这可以解决代码中的问题,即线程在启动后短时间内不会被计为启动。

I can't figure out when anyone would ever want to use detach. I'd use something like

use threads;

my %workers;

sub start_worker {
   my $thread = threads->create(@_);
   $workers{$thread->tid} = $thread;
   return $thread;
}

sub collect_finished_workers {
   for my $thread (threads->list(threads::joinable)) {
      $thread->join()
         if delete($workers{$threads->tid});  # Don't assume we own all threads.
   }
}

sub get_worker_count {
   collect_finished_workers();
   return 0+keys(%workers);
}

Note that this fixes the problem in your code where a thread isn't counted as started for a short while after it has started.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文