Skip to content

Commit

Permalink
Replaced the simple sleep wait, with a tokio Notify barrier
Browse files Browse the repository at this point in the history
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
  • Loading branch information
DjLogozzo authored and apognu committed Jan 22, 2022
1 parent b7aa752 commit e6eb3e7
Show file tree
Hide file tree
Showing 3 changed files with 6 additions and 3 deletions.
3 changes: 2 additions & 1 deletion src/greeter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ use i18n_embed::DesktopLanguageRequester;
use tokio::{
net::UnixStream,
process::Command,
sync::{RwLock, RwLockWriteGuard},
sync::{Notify, RwLock, RwLockWriteGuard},
};
use zeroize::Zeroize;

Expand Down Expand Up @@ -87,6 +87,7 @@ pub struct Greeter {

pub power_commands: HashMap<PowerOption, String>,
pub power_command: Option<Command>,
pub power_command_notify: Arc<Notify>,
pub power_setsid: bool,

pub working: bool,
Expand Down
5 changes: 3 additions & 2 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,16 +70,17 @@ async fn run() -> Result<(), Box<dyn Error>> {

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
}
}
});
Expand Down
1 change: 1 addition & 0 deletions src/power.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<RwLock<Greeter>>, mut command: Command) {
Expand Down

0 comments on commit e6eb3e7

Please sign in to comment.