fix race condition in semaphore cleanup code

tags: relevant