螺纹的轻量叉替换 [英] Lightweight fork replacement for threads

查看:40
本文介绍了螺纹的轻量叉替换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在下面使用类似于 threads asyncfasync.我是不是忘记了什么,这里是否有一些特殊情况没有涵盖?

I would like to use fasync below similar to threads async. Am I forgetting something, are there some corner cases which are not covered here?

sub fasync(&) {
  my ($worker) = @_;

  my $pid = fork() // die "can't fork!";

  if (!$pid) {
    $worker->();
    exit(0);
  }

  return sub {
    my ($flags) = @_;
    return waitpid($pid, $flags // 0);
  }
}

my @join = map {
  my $job = $_;
  fasync {

    print "$job\n";
  };
} 1 .. 10;

$_->() for @join;

推荐答案

看起来它应该可以正常工作,尽管应该对 fork 进行错误检查(它返回 undef 失败),如果您想在子级和父级之间或不同子级之间使用任何通信方式,则需要详细说明.

That looks like it should work just fine, although there should be an error check on fork (it returns undef on failure), and it needs elaboration if you want any means of communicating between the children and the parent, or between different children.

这篇关于螺纹的轻量叉替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆