Improve semaphore implementation