chaokunyang commented on code in PR #2810:
URL: https://github.com/apache/fory/pull/2810#discussion_r2452201875
##########
rust/fory-core/src/util.rs:
##########
@@ -129,3 +131,32 @@ pub fn get_ext_actual_type_id(type_id: u32,
register_by_name: bool) -> u32 {
TypeId::EXT as u32
}
}
+
+pub struct Spinlock<T> {
+ data: UnsafeCell<T>,
+ flag: AtomicBool,
+}
+
+unsafe impl<T: Send + Sync> Send for Spinlock<T> {}
+unsafe impl<T: Send + Sync> Sync for Spinlock<T> {}
+
+impl<T> Spinlock<T> {
+ pub fn new(data: T) -> Self {
+ Spinlock {
+ data: UnsafeCell::new(data),
+ flag: AtomicBool::new(false),
+ }
+ }
+
+ pub fn lock(&self) -> &mut T {
+ while self.flag.compare_exchange(false, true, Ordering::Acquire,
Ordering::Relaxed).is_err() {
+ std::hint::spin_loop();
Review Comment:
We need yield here:
```rust
pub fn lock(&self) -> SpinlockGuard<'_, T> {
let mut spins = 0;
while self
.flag
.compare_exchange(false, true, Ordering::Acquire,
Ordering::Relaxed)
.is_err()
{
// Spin for a few iterations
if spins < 10 {
std::hint::spin_loop();
spins += 1;
} else {
// Then yield to the scheduler
thread::yield_now();
spins = 0; // reset spin counter
}
}
SpinlockGuard { lock: self }
}
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]