From e6eb3e70249c2edd47cc117748c7f6a05572d871 Mon Sep 17 00:00:00 2001 From: Dee-Jay Logozzo Date: Fri, 19 Nov 2021 19:43:46 +1100 Subject: [PATCH] Replaced the simple sleep wait, with a tokio `Notify` barrier This is still a fairly simple band-aid solution, however it is a more eligant solution as it removes the free-running aspect of the loop entirely, only processing the possibility of a `power_command` if we've been notified that there is one to process --- src/greeter.rs | 3 ++- src/main.rs | 5 +++-- src/power.rs | 1 + 3 files changed, 6 insertions(+), 3 deletions(-) diff --git a/src/greeter.rs b/src/greeter.rs index 605e880..3121a2f 100644 --- a/src/greeter.rs +++ b/src/greeter.rs @@ -14,7 +14,7 @@ use i18n_embed::DesktopLanguageRequester; use tokio::{ net::UnixStream, process::Command, - sync::{RwLock, RwLockWriteGuard}, + sync::{Notify, RwLock, RwLockWriteGuard}, }; use zeroize::Zeroize; @@ -87,6 +87,7 @@ pub struct Greeter { pub power_commands: HashMap, pub power_command: Option, + pub power_command_notify: Arc, pub power_setsid: bool, pub working: bool, diff --git a/src/main.rs b/src/main.rs index 50fb132..5cce98e 100644 --- a/src/main.rs +++ b/src/main.rs @@ -70,16 +70,17 @@ async fn run() -> Result<(), Box> { tokio::task::spawn({ let greeter = greeter.clone(); + let notify = greeter.read().await.power_command_notify.clone(); async move { loop { + notify.notified().await; + let command = greeter.write().await.power_command.take(); if let Some(command) = command { power::run(&greeter, command).await; } - - tokio::time::sleep(std::time::Duration::from_millis(100)).await } } }); diff --git a/src/power.rs b/src/power.rs index 245477f..9a0f688 100644 --- a/src/power.rs +++ b/src/power.rs @@ -50,6 +50,7 @@ pub fn power(greeter: &mut Greeter, option: PowerOption) { }; greeter.power_command = Some(command); + greeter.power_command_notify.notify_one(); } pub async fn run(greeter: &Arc>, mut command: Command) {