3 # example2.pl - Limiting process concurrency using IPC::Semaphore::Concurrency
5 # Author: Thomas Guyot-Sionnest <tguyot@gmail.com>
7 # This in a perl example of using semaphores to limit concurrent processes
8 # doing a specific task and queue them up.
10 # This code is released to the public domain.
15 use IPC
::Semaphore
::Concurrency
;
17 use vars
qw($sem_path_name $sem_max $max_queue);
19 # Semaphore pathname for key generation (will be created if missing)
20 $sem_path_name = '/tmp/sem_test_b0c2';
21 # Max concurrency - also used as semaphore proj_id
23 # Max number of queued processes (-1 eq infinite)
26 my $sem = IPC::Semaphore::Concurrency->new(
27 path => $sem_path_name,
30 ) or die("Failed to create semaphore: $!");
31 if (@ARGV > 0 && $ARGV[0] eq 'reset') {
36 print "\nbegin val: ".$sem->getval(0)."\n";
38 if ((my $res = $sem->acquire(
46 } elsif ($!{EWOULDBLOCK}) {
47 print "Too many jobs queued up ($max_queue)!\n";
49 die("Unexpected Error: $!");
52 print "\nend val: ".$sem->getval(0)."\n"; # Value will be re-incremented as soon as the process exits