# Perl replica of using a Barrier with an Action # https://superfastpython.com/multiprocessing-barrier-in-python/ use MCE::Simple -strict, -signatures; use MCE::Barrier; use Time::HiRes 'sleep'; STDOUT->autoflush(1); sub report () { # report once all processes are done say "All processes have their result"; } sub task ($barrier, $number) { # generate a unique value and block for a moment my $value = rand() * 10; sleep($value); # report result say "Process ${number} done, got: ${value}"; # wait on all other processes to complete my ($remaining, $error) = $barrier->wait; # an alternative to using the "action" argument if ($remaining == 0) { say "I, process ${number}, was last..."; } } sub main () { # create a barrier, not including the main process my $barrier = MCE::Barrier->new(5, before_release => \&report); # create the worker processes spawn task($barrier, $_) for 1..5; # reap the worker processes sync; } main(); __END__ Process 1 done, got: 1.25912054515542 Process 5 done, got: 2.02445819116296 Process 4 done, got: 4.33312377966107 Process 3 done, got: 6.64178936815919 Process 2 done, got: 8.9504549566573 All processes have their result I, process 2, was last...