This is not an endless loop; it is good practice when working with the TAS algorithm (test and set). What the loop does is (a) read from memory (should be volatile semantics) (b) calculate a new value (c) write a new value if the old value has not changed.
In the database area, this is called optimistic locking. It exploits the fact that most concurrent updates for shared memory are invalid, in which case it is the cheapest way to do this.
In fact, this is basically what Unexpected Lock will do in the case of an uncontrolled case. It will read the value of the lock, and if it is unlocked, it will execute the CAS of the thread identifier, and if this happens, the lock will be saved. If this fails, someone else got a lock. Locks, although dealing with failure, are much more complicated than just repeating the operation over and over. They will continue to read it for a while until the lock is quickly unlocked (spin lock), and then usually goes into sleep mode so that other flows reach their turn (exponential shutdown).
source share