in reply to Effective use of IPC::Semaphore to limit number of concurrent executions of a scxipt
A semaphore is basically an atomic counter. It guarantees that only one counter operation(increment or decrement) will occur no matter how many processes or threads are trying to operate on it simultaneously. Also, the counter may not be decremented lower than 0. Any attempt to decrement the counter when it is zero will 'block' , unless the IPC_NOWAIT flag is set on your operations, in which case it will fail with an errno set to EAGAIN or EWOULDBLOCK. The process will block until someone increments that semaphore. Once that happens if there is more than one process waiting to decrement it back to zero, only 1 will succeed.
Typically semaphores are used sort of like mutexes to prevent two processes from touching the same piece of shared memory at the same time.
However, your use for them is fine as well. The only thing is that you don't want to be incrementing it using getval setval. You want to use the 'op' method instead. Your code should look something this like this:
NOTES:use IPC::SysV qw/SEM_UNDO IPC_CREAT ftok/ ; use IPC::Semaphore ; # start script $flags = PERMISSIONS ; $sem = new IPC::Semaphore(ftok($0, 0), 1, $flags) ; unless($sem) { # we must be the first one $sem = new IPC::Semaphore($id, 1, $flags | IPC_CREAT) $sem->setval(0, 100) ; } ## ## Decrement the #0 semaphore by 1 ## $sem->op(0, -1, SEM_UNDO) ; # blocks if semaphore is zero # # DO SCRIPT STUFF # ## ## Increment #0 semaphore by 1 ## $sem->op(0, 1, SEM_UNDO) ; # once past this point, any script waiting can proceed # done
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Effective use of IPC::Semaphore to limit number of concurrent executions of a scxipt
by atcroft (Abbot) on Oct 16, 2003 at 10:04 UTC | |
by ptkdb (Monk) on Oct 16, 2003 at 12:23 UTC | |
by ptkdb (Monk) on Oct 16, 2003 at 15:03 UTC |