Debugged version, using locks instead of semaphores