Let's reverse the question. Why do you expect to get the expected output by executing the first set of code? Why do you expect the whole loop to be atomic, when you grab (and release) the lock per each iteration of the loop?