Skip to content

Instantly share code, notes, and snippets.

@dakkar
Created May 9, 2018 15:12
Show Gist options
  • Save dakkar/c11cd28f2fcc9878b9c56952055dcd60 to your computer and use it in GitHub Desktop.
Save dakkar/c11cd28f2fcc9878b9c56952055dcd60 to your computer and use it in GitHub Desktop.
weird interaction between `fork` and threads in perl 5 24.0
#!/usr/bin/env perl
use strict;
use warnings;
use 5.020;
use threads;
sub run_child {
my ($value) = @_;
my $tid = threads->tid;
if (my $pid=fork()) {
say "$tid waiting for $pid";
# the waitpid() seems to block all threads, not just the
# current one
# my $exit = waitpid($pid,0);
# say "$tid - $pid exited with $exit";
}
else {
say "$$ spawned from $tid, value $value";
say "$$ thread: ".$_->tid for threads->list;
sleep(2);
exit $value;
}
}
my @threads = map { threads->create(\&run_child,$_) } 1..10;
while (my @running = threads->list) {
say "$$ joining " . $running[0]->tid;
$running[0]->join;
}
# this is to wait for the children to exit, since we can't use the
# waitpid
sleep(5);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment