Skip to content

Commit 12a93ed

Browse files
committed
Add a block until shutdown.
1 parent 49140e9 commit 12a93ed

File tree

2 files changed

+42
-1
lines changed

2 files changed

+42
-1
lines changed

crates/ytermusic/src/shutdown.rs

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,46 @@ use std::{
77

88
use log::info;
99

10+
use std::sync::{Condvar, Mutex};
11+
12+
pub struct SharedEvent {
13+
lock: Mutex<bool>,
14+
cvar: Condvar,
15+
}
16+
17+
impl SharedEvent {
18+
// const fn allows this to be called in a static context
19+
pub const fn new() -> Self {
20+
Self {
21+
lock: Mutex::new(false),
22+
cvar: Condvar::new(),
23+
}
24+
}
25+
26+
/// Blocks the current thread until notify() is called.
27+
pub fn wait(&self) {
28+
let mut ready = self.lock.lock().unwrap();
29+
while !*ready {
30+
ready = self.cvar.wait(ready).unwrap();
31+
}
32+
}
33+
34+
/// Wakes up ALL waiting threads.
35+
pub fn notify(&self) {
36+
let mut ready = self.lock.lock().unwrap();
37+
*ready = true;
38+
self.cvar.notify_all();
39+
}
40+
}
41+
42+
// Global static initialization
43+
static SHUTDOWN_WAKER: SharedEvent = SharedEvent::new();
44+
45+
#[allow(dead_code)]
46+
pub fn block_until_shutdown() {
47+
SHUTDOWN_WAKER.wait();
48+
}
49+
1050
static SHUTDOWN_SENT: AtomicBool = AtomicBool::new(false);
1151

1252
pub fn is_shutdown_sent() -> bool {
@@ -30,5 +70,6 @@ impl Future for ShutdownSignal {
3070

3171
pub fn shutdown() {
3272
SHUTDOWN_SENT.store(true, Ordering::Relaxed);
73+
SHUTDOWN_WAKER.notify();
3374
info!("Shutdown signal sent, waiting for shutdown");
3475
}

crates/ytermusic/src/structures/media.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -167,7 +167,7 @@ pub fn run_window_handler(_updater: &Sender<ManagerMessage>) -> Option<()> {
167167
use crate::is_shutdown_sent;
168168

169169
loop {
170-
if is_shutdown_sent() {
170+
if crate::shutdown::block_until_shutdown() && is_shutdown_sent() {
171171
use std::process::exit;
172172

173173
info!("event loop closed");

0 commit comments

Comments
 (0)