Specifically, to address the issue described on the atomic above I think you need to change this compare_and_swap to work like this:
0 => unreachable!
1 => set to 0, and break the loop
n => set to 1, and continue the loop