use strict; use warnings; use Time::HiRes 'sleep'; use threads; use threads::shared; my $baton:shared = 0; sub sprinter { my ($no_of_threads,$sleep) = @_; my $id = threads->self->tid; warn ("Thread $id started\n"); while (1) { lock ($baton); cond_wait ($baton) until $baton == $id; warn ("Thread $id has the baton\n"); sleep ($sleep); $baton = int (rand ($no_of_threads)) until $baton != $id; warn ("Thread $id passing the baton to thread $baton\n"); cond_signal ($baton); # cond_broadcast ($baton); } } my ($no_of_sprinters, $sleep ) = @ARGV; $no_of_sprinters ||= 3; my @threads; push @threads,threads->new (\&sprinter,$no_of_sprinters, $sleep) for 1..$no_of_sprinters; sleep 1; while(1){ lock ($baton); cond_wait ($baton) until $baton == 0; warn ("Thread 0 has the baton\n"); sleep ($sleep); $baton = int (rand ($no_of_sprinters)) until $baton != 0; warn ("Thread 0 passing the baton to thread $baton\n"); cond_signal ($baton); # cond_broadcast ($baton); }