perf: use atomics for controller progress and state
This commit is contained in:
parent
93dd775f3c
commit
971374f60b
3 changed files with 29 additions and 10 deletions
|
|
@ -1,7 +1,11 @@
|
|||
use std::sync::{Arc, Mutex};
|
||||
use atomic_float::AtomicF32;
|
||||
use num_enum::{IntoPrimitive, TryFromPrimitive};
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{self, AtomicU16};
|
||||
use tokio::sync::Notify;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, IntoPrimitive, TryFromPrimitive)]
|
||||
#[repr(u16)]
|
||||
pub enum ControllerState {
|
||||
Cancelled,
|
||||
Failed,
|
||||
|
|
@ -11,8 +15,8 @@ pub enum ControllerState {
|
|||
|
||||
#[derive(Debug)]
|
||||
struct ControllerInner {
|
||||
state: Mutex<ControllerState>,
|
||||
progress: Mutex<f32>,
|
||||
state: AtomicU16,
|
||||
progress: AtomicF32,
|
||||
notify: Notify,
|
||||
}
|
||||
|
||||
|
|
@ -27,8 +31,8 @@ impl Default for Controller {
|
|||
Self {
|
||||
primary: true,
|
||||
inner: Arc::new(ControllerInner {
|
||||
state: Mutex::new(ControllerState::Running),
|
||||
progress: Mutex::new(0.0),
|
||||
state: AtomicU16::new(ControllerState::Running.into()),
|
||||
progress: AtomicF32::new(0.0),
|
||||
notify: Notify::new(),
|
||||
}),
|
||||
}
|
||||
|
|
@ -50,19 +54,24 @@ impl Controller {
|
|||
}
|
||||
|
||||
pub fn progress(&self) -> f32 {
|
||||
*self.inner.progress.lock().unwrap()
|
||||
self.inner.progress.load(atomic::Ordering::Relaxed)
|
||||
}
|
||||
|
||||
pub fn set_progress(&self, progress: f32) {
|
||||
*self.inner.progress.lock().unwrap() = progress;
|
||||
self.inner
|
||||
.progress
|
||||
.swap(progress, atomic::Ordering::Relaxed);
|
||||
}
|
||||
|
||||
pub fn state(&self) -> ControllerState {
|
||||
*self.inner.state.lock().unwrap()
|
||||
ControllerState::try_from(self.inner.state.load(atomic::Ordering::Relaxed))
|
||||
.unwrap_or(ControllerState::Failed)
|
||||
}
|
||||
|
||||
pub fn set_state(&self, state: ControllerState) {
|
||||
*self.inner.state.lock().unwrap() = state;
|
||||
self.inner
|
||||
.state
|
||||
.store(state.into(), atomic::Ordering::Relaxed);
|
||||
self.inner.notify.notify_waiters();
|
||||
}
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue