sem_wait and fixed memory leaks