# Perl replica of using a Barrier with a Timeout # https://superfastpython.com/multiprocessing-barrier-in-python/ use MCE::Simple -strict, -signatures; use MCE::Barrier; use Time::HiRes 'sleep'; use Try::Tiny; STDOUT->autoflush(1); 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; # or via exception handling try { $barrier->wait; } catch { # pass }; } sub main () { # create a barrier plus one for the main process my $barrier = MCE::Barrier->new(5 + 1); # create the worker processes spawn task($barrier, $_) for 1..5; # wait for all processes to finish # my ($remaining, $error) = $barrier->wait; # or via exception handling try { $barrier->wait(timeout => 5); say "All processes have their result"; } catch { # $_ = "Operation timed out ..." say "Some processes did not finish on time..."; }; # reap the worker processes sync; } main(); __END__ Process 2 done, got: 2.20488202831806 Process 1 done, got: 4.51354761681618 Some processes did not finish on time... Process 5 done, got: 5.27888526282371 Process 4 done, got: 7.58755085132183 Process 3 done, got: 9.89621643981994