in reply to Re^2: Effective use of IPC::Semaphore to limit number of concurrent executions of a scxipt
in thread Effective use of IPC::Semaphore to limit number of concurrent executions of a scxipt

You don't need to do a 'getval(0)' to check the value of the semaphore. If you set the flags to SEM_UNDO | IPC_NOWAIT, and check the return result and $!. If $! is EAGAIN then the semaphore value was 0 so no slots would be available and $sem->op() returned without altering the semaphore's value.
use Errno qw/EAGAIN EINTR/ ; $result = $sem->op(0, -1, SEM_UNDO | IPC_NOWAIT) if( !$result && $! == EAGAIN ) { # semaphore was zero, no slots available print "BUSY, try later\n" ; exit(0) ; } die "op failed: $!" unless $result ; # op failed for some other reason ## ## lock acquired ##
Blocking isn't really as bad as it sounds. The process will just wait until one of other instances finishes and then increments the semaphore to something greater than 0. How long that takes depends on how many others are competing to decrement the semaphore at the same time.

If you want, you can add a time out using 'alarm'.

alarm(5) ; # five seconds $success = semop $result = int $! ; # capture the value of errno alarm(0) ; # cancel alarm(if still active) if( !$sucess && $result == EINTR ) { # timed out }
  • Comment on Re: Re^2: Effective use of IPC::Semaphore to limit number of concurrent executions of a scxipt
  • Select or Download Code