kaist-cp/cs431

[Question] Why use AtomicBool instead of non-atomic bool in Node of CLH Lock?

Closed this issue · 2 comments

Why do we use AtomicBool in node of CLH Lock?

struct Node {
locked: AtomicBool,
}

Isn't it enough to use non-atomic bool since we only read in lock() and write unlock()?

while unsafe { (*prev).locked.load(Acquire) } {

unsafe fn unlock(&self, token: Self::Token) {
unsafe { (*token.0).locked.store(false, Release) };
}

Non-atomically reading from or writing to a location that can be concurrently accessed by multiple threads are always data races. This condition is formally defined in the language semantics (precisely, memory model). Such situation is considered as an undefined behavior, and compilers might perform aggressive optimization while assuming that such situation never happens. This is the reason why we should use AtomicBool even if we don't use CAS, FAA, etc.

Reference: https://stackoverflow.com/questions/72639534/why-is-atomic-bool-needed-to-avoid-data-race

Understood! Thank you!