The problem here is wait, it will store the current variables on the stack when its called and will restore them later, however, its not guaranteed that the variables will end up on the same address as before, so your semaphore function will change something completely different and your sempahore variable will never change.