But failed the interview without any specific feedback.
I looked online and found very similar solutions to mine, one was different as it's using sleep instead of yield, but I think the latter is better for real-time as it minimizez the wait time.
Do you think this solution is not correct? If so, how can it be made better?
Your atomic orderings are incorrect. The simplest fix is to use Acquire when locking and Release when unlocking.
I think it would be better to use spin_loop instead of yield_now, but this is dependent on what kind of spin lock you're trying to make.
The most important problem, though, is that you use false to mean "unlocked", but then break out of the loop when there is a true.
if self.lock.swap(true, Ordering::Acquire) {
break;
}
Usually when you break out of the loop, it'll be right after the same thread swapped in a true and you won't notice any issue, but occasionally it will be right after another thread swapped in a true and you'll have 2 or more threads that think they have exclusive access.
The fix is simple.
if !self.lock.swap(true, Ordering::Acquire) {
break;
}
Note that if you use a while loop, the condition is flipped.
while self.lock.swap(true, Ordering::Acquire) {
std::hint::spin_loop();
}