Skip to content

Commit

Permalink
Guard calls into avrt.dll with a Mutex
Browse files Browse the repository at this point in the history
  • Loading branch information
yjugl committed Mar 13, 2024
1 parent bcda8f3 commit 9ea70b5
Showing 1 changed file with 17 additions and 2 deletions.
19 changes: 17 additions & 2 deletions src/rt_win.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
use std::sync::Mutex;
use std::sync::MutexGuard;
use std::sync::OnceLock;

use windows_sys::s;
use windows_sys::Win32::Foundation::GetLastError;
use windows_sys::Win32::Foundation::FALSE;
Expand Down Expand Up @@ -28,7 +32,10 @@ impl RtPriorityHandleInternal {
pub fn demote_current_thread_from_real_time_internal(
rt_priority_handle: RtPriorityHandleInternal,
) -> Result<(), AudioThreadPriorityError> {
let rv = unsafe { AvRevertMmThreadCharacteristics(rt_priority_handle.task_handle) };
let rv = {
let _guard = avrt_lock();
unsafe { AvRevertMmThreadCharacteristics(rt_priority_handle.task_handle) }
};
if rv == FALSE {
return Err(AudioThreadPriorityError::new(&format!(
"Unable to restore the thread priority ({:?})",
Expand All @@ -50,7 +57,10 @@ pub fn promote_current_thread_to_real_time_internal(
) -> Result<RtPriorityHandleInternal, AudioThreadPriorityError> {
let mut task_index = 0u32;

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

if handle.task_handle == 0 {
Expand Down Expand Up @@ -100,3 +110,8 @@ 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 9ea70b5

Please sign in to comment.