1
Fork 0
mirror of https://github.com/RGBCube/superfreq synced 2025-07-27 17:07:44 +00:00

engine: fix race condition

This commit is contained in:
NotAShelf 2025-05-18 03:15:34 +03:00
parent 8866eb4485
commit c570a327ab
No known key found for this signature in database
GPG key ID: 29D95B64378DB4BF

View file

@ -68,13 +68,26 @@ impl TurboHysteresis {
} }
/// Initialize the state with a specific value if not already initialized /// Initialize the state with a specific value if not already initialized
/// Uses atomic `compare_exchange` to ensure only one thread can initialize the state
fn initialize_with(&self, initial_state: bool) -> bool { fn initialize_with(&self, initial_state: bool) -> bool {
if !self.initialized.load(Ordering::Acquire) { // Try to atomically change initialized from false to true
self.previous_state.store(initial_state, Ordering::Release); // This ensures only one thread can win the initialization race
self.initialized.store(true, Ordering::Release); match self.initialized.compare_exchange(
return initial_state; false, // expected: not initialized
true, // desired: mark as initialized
Ordering::AcqRel, // success ordering: acquire+release for memory visibility
Ordering::Acquire, // failure ordering: just need to acquire the current value
) {
Ok(_) => {
// We won the race to initialize - set the initial state
self.previous_state.store(initial_state, Ordering::Release);
initial_state
}
Err(_) => {
// Another thread already initialized it - read the current state
self.previous_state.load(Ordering::Acquire)
}
} }
self.previous_state.load(Ordering::Acquire)
} }
/// Update the turbo state for hysteresis /// Update the turbo state for hysteresis