Don't use semaphores to serialize access to an undefined number of resources. There is no way (yet) to know before locking if a semaphore is already locked, thus not being able to fully release the semaphore and occupying a semaphore resource for an undefined time.
A possible solution is to build a shared mem pool and store there the current number of locks for a semaphore id.
Cheers,
Horaci Cuevas