mpapec
mpapec

Reputation: 50667

Lightweight fork replacement for threads

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;

Upvotes: 1

Views: 247

Answers (1)

hobbs
hobbs

Reputation: 240482

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.

Upvotes: 4

Related Questions