The definition of the critical section needs to be outside the function - otherwise the critical blocks are blocking on different objects.