gpui: Fix race condition when upgrading a weak reference (#30952)

Release Notes:

- N/A
This commit is contained in:
laizy 2025-05-30 23:18:25 +08:00 committed by GitHub
parent 97c01c6720
commit c4dbaa91f0
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 28 additions and 13 deletions

View file

@ -1,3 +1,5 @@
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering::SeqCst;
#[cfg(any(test, feature = "test-support"))]
use std::time::Duration;
@ -108,3 +110,18 @@ impl std::fmt::Debug for CwdBacktrace<'_> {
fmt.finish()
}
}
/// Increment the given atomic counter if it is not zero.
/// Return the new value of the counter.
pub(crate) fn atomic_incr_if_not_zero(counter: &AtomicUsize) -> usize {
let mut loaded = counter.load(SeqCst);
loop {
if loaded == 0 {
return 0;
}
match counter.compare_exchange_weak(loaded, loaded + 1, SeqCst, SeqCst) {
Ok(x) => return x + 1,
Err(actual) => loaded = actual,
}
}
}