Refactoring: extract semaphore logic.