use std::any::Any;
#[cfg(windows)]
pub fn acquire_global_lock(name: &str) -> Box<dyn Any> {
use std::ffi::CString;
use std::io;
use winapi::shared::ntdef::HANDLE;
use winapi::um::handleapi::CloseHandle;
use winapi::um::synchapi::{CreateMutexA, ReleaseMutex, WaitForSingleObject};
use winapi::um::winbase::{INFINITE, WAIT_ABANDONED, WAIT_OBJECT_0};
struct Handle(HANDLE);
impl Drop for Handle {
fn drop(&mut self) {
unsafe {
CloseHandle(self.0);
}
}
}
struct Guard(Handle);
impl Drop for Guard {
fn drop(&mut self) {
unsafe {
ReleaseMutex((self.0).0);
}
}
}
let cname = CString::new(name).unwrap();
unsafe {
let mutex = CreateMutexA(std::ptr::null_mut(), 0, cname.as_ptr());
if mutex.is_null() {
panic!(
"failed to create global mutex named `{}`: {}",
name,
io::Error::last_os_error()
);
}
let mutex = Handle(mutex);
match WaitForSingleObject(mutex.0, INFINITE) {
WAIT_OBJECT_0 | WAIT_ABANDONED => {}
code => {
panic!(
"WaitForSingleObject failed on global mutex named \
`{}`: {} (ret={:x})",
name,
io::Error::last_os_error(),
code
);
}
}
Box::new(Guard(mutex))
}
}
#[cfg(not(windows))]
pub fn acquire_global_lock(_name: &str) -> Box<dyn Any> {
Box::new(())
}