Single watcher thread

This commit is contained in:
hodasemi 2018-08-15 21:52:26 +02:00
parent dd4210ad6f
commit 21cc37e80c

View file

@ -11,6 +11,7 @@ use std::cell::RefCell;
use std::ops::DerefMut; use std::ops::DerefMut;
use std::sync::{Arc, Mutex, MutexGuard}; use std::sync::{Arc, Mutex, MutexGuard};
use std::thread; use std::thread;
use std::thread::JoinHandle;
use std::time; use std::time;
macro_rules! check_option { macro_rules! check_option {
@ -30,6 +31,7 @@ pub struct Song {
pub struct MediaData { pub struct MediaData {
playlist: RefCell<Vec<Song>>, playlist: RefCell<Vec<Song>>,
current_song: Mutex<RefCell<Option<LockedAudio>>>, current_song: Mutex<RefCell<Option<LockedAudio>>>,
watcher_thread: RefCell<Option<JoinHandle<()>>>,
} }
fn guild_id(channel_id: ChannelId) -> Option<GuildId> { fn guild_id(channel_id: ChannelId) -> Option<GuildId> {
@ -57,6 +59,10 @@ impl MediaData {
self.current_song.lock().unwrap() self.current_song.lock().unwrap()
} }
fn reset_thread(&self) {
*self.watcher_thread.borrow_mut() = None;
}
fn start_thread( fn start_thread(
media: &Arc<MediaData>, media: &Arc<MediaData>,
channel_id: ChannelId, channel_id: ChannelId,
@ -67,7 +73,10 @@ impl MediaData {
let media_clone = media.clone(); let media_clone = media.clone();
let manager_clone = manager_lock.clone(); let manager_clone = manager_lock.clone();
thread::spawn(move || loop { let mut watcher_mut = media.watcher_thread.borrow_mut();
if watcher_mut.is_none() {
*watcher_mut = Some(thread::spawn(move || loop {
{ {
let song_lock = media_clone.song_mut(); let song_lock = media_clone.song_mut();
let mut borrow = song_lock.borrow_mut(); let mut borrow = song_lock.borrow_mut();
@ -87,6 +96,8 @@ impl MediaData {
.lock() .lock()
.remove(check_option!(guild_id(channel_id))); .remove(check_option!(guild_id(channel_id)));
media_clone.reset_thread();
println!("left channel"); println!("left channel");
return; return;
@ -120,6 +131,8 @@ impl MediaData {
.lock() .lock()
.remove(check_option!(guild_id(channel_id))); .remove(check_option!(guild_id(channel_id)));
media_clone.reset_thread();
println!("left channel"); println!("left channel");
return; return;
@ -128,7 +141,8 @@ impl MediaData {
let five_sec = time::Duration::from_secs(5); let five_sec = time::Duration::from_secs(5);
thread::sleep(five_sec); thread::sleep(five_sec);
}); }));
}
} }
fn next_song( fn next_song(
@ -172,6 +186,7 @@ impl Default for MediaData {
MediaData { MediaData {
playlist: RefCell::new(Vec::new()), playlist: RefCell::new(Vec::new()),
current_song: Mutex::new(RefCell::new(None)), current_song: Mutex::new(RefCell::new(None)),
watcher_thread: RefCell::new(None),
} }
} }
} }