Add semaphore and fix some bug