Skip to content

Commit

Permalink
Replace global lock by warmup
Browse files Browse the repository at this point in the history
  • Loading branch information
yjugl committed Mar 13, 2024
1 parent 9ea70b5 commit 87e90c7
Showing 1 changed file with 13 additions and 16 deletions.
29 changes: 13 additions & 16 deletions src/rt_win.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
use std::sync::Mutex;
use std::sync::MutexGuard;
use std::sync::OnceLock;
use std::sync::Once;

use windows_sys::s;
use windows_sys::Win32::Foundation::GetLastError;
Expand Down Expand Up @@ -32,10 +30,7 @@ impl RtPriorityHandleInternal {
pub fn demote_current_thread_from_real_time_internal(
rt_priority_handle: RtPriorityHandleInternal,
) -> Result<(), AudioThreadPriorityError> {
let rv = {
let _guard = avrt_lock();
unsafe { AvRevertMmThreadCharacteristics(rt_priority_handle.task_handle) }
};
let rv = unsafe { AvRevertMmThreadCharacteristics(rt_priority_handle.task_handle) };
if rv == FALSE {
return Err(AudioThreadPriorityError::new(&format!(
"Unable to restore the thread priority ({:?})",
Expand All @@ -55,12 +50,19 @@ pub fn promote_current_thread_to_real_time_internal(
_audio_buffer_frames: u32,
_audio_samplerate_hz: u32,
) -> Result<RtPriorityHandleInternal, AudioThreadPriorityError> {
static WARMUP: Once = Once::new();
WARMUP.call_once(|| {
if let Ok(handle) = promote_current_thread() {
let _ = demote_current_thread_from_real_time_internal(handle);
}
});
promote_current_thread()
}

fn promote_current_thread() -> Result<RtPriorityHandleInternal, AudioThreadPriorityError> {
let mut task_index = 0u32;

let handle = {
let _guard = avrt_lock();
unsafe { AvSetMmThreadCharacteristicsA(s!("Audio"), &mut task_index) }
};
let handle = unsafe { AvSetMmThreadCharacteristicsA(s!("Audio"), &mut task_index) };
let handle = RtPriorityHandleInternal::new(task_index, handle);

if handle.task_handle == 0 {
Expand Down Expand Up @@ -110,8 +112,3 @@ fn test_successful_api_use_3() {
println!("result: {result:?}");
assert!(result.is_ok());
}

fn avrt_lock() -> MutexGuard<'static, ()> {
static CELL: OnceLock<Mutex<()>> = OnceLock::new();
CELL.get_or_init(|| Mutex::new(())).lock().unwrap()
}

0 comments on commit 87e90c7

Please sign in to comment.