feat: wait for threads to be ready on linux

v1
paring 2022-11-05 13:43:32 +09:00
parent 70384e56bb
commit 18ea974db7
Signed by: pikokr
GPG Key ID: DB839724AD14EC9F
2 changed files with 35 additions and 3 deletions

View File

@ -1,4 +1,8 @@
use std::{fs, sync::Arc, thread};
use std::{
fs,
sync::{atomic::AtomicUsize, Arc},
thread,
};
use cancellation::CancellationTokenSource;
@ -12,6 +16,7 @@ pub static mut CANCELLATION_TOKEN: Option<Arc<CancellationTokenSource>> = None;
pub static mut STARTED: bool = false;
pub static mut ERROR: Option<Error> = None;
pub static mut ARC_READY_COUNT: Option<Arc<AtomicUsize>> = None;
pub fn start(callback: fn(Event)) -> Result<(), Error> {
if unsafe { STARTED } {
@ -35,8 +40,11 @@ pub fn start(callback: fn(Event)) -> Result<(), Error> {
unsafe {
CANCELLATION_TOKEN = Some(Arc::new(cts));
ARC_READY_COUNT = Some(Arc::new(AtomicUsize::new(0)));
}
let mut count = 0;
for path in dir {
let filename = path.expect("Failed to get dir entry").file_name();
let filename: String = match filename.to_str() {
@ -50,7 +58,6 @@ pub fn start(callback: fn(Event)) -> Result<(), Error> {
.name("SkyHook".into())
.spawn(move || {
if let Err(err) = start_reader(format!("/dev/input/{}", filename), callback) {
println!("{:?}", err);
unsafe {
ERROR = Some(err);
}
@ -63,6 +70,8 @@ pub fn start(callback: fn(Event)) -> Result<(), Error> {
message: format!("Failed to spawn thread: {:?}", err),
});
}
count += 1;
}
}
@ -72,6 +81,23 @@ pub fn start(callback: fn(Event)) -> Result<(), Error> {
});
}
while unsafe {
ERROR.is_none()
&& !{
if let Some(arc) = &ARC_READY_COUNT {
arc.load(std::sync::atomic::Ordering::Relaxed) < count
} else {
false
}
}
} {
thread::yield_now();
}
if let Some(err) = unsafe { &ERROR } {
return Err(err.clone());
}
unsafe {
STARTED = true;
}

View File

@ -2,7 +2,7 @@ use std::{fs::File, io::Read, time::SystemTime};
use crate::types::{Error, Event, EventData};
use super::CANCELLATION_TOKEN;
use super::{ARC_READY_COUNT, CANCELLATION_TOKEN};
fn convert_bit(bits: &[u8]) -> u16 {
let mut result: u16 = 0;
@ -23,6 +23,12 @@ pub fn start_reader(file_path: String, callback: fn(Event)) -> Result<(), Error>
}
};
unsafe {
if let Some(arc) = &ARC_READY_COUNT {
arc.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
}
}
loop {
let mut buffer = [0; 24];