44 lines
1.1 KiB
Go
44 lines
1.1 KiB
Go
//go:build windows
|
|
|
|
package shelllock
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
"runtime"
|
|
|
|
"golang.org/x/sys/windows"
|
|
)
|
|
|
|
const mutexName = `Local\ReimsGo-Test-MSYS`
|
|
|
|
func Acquire() (func(), error) {
|
|
runtime.LockOSThread()
|
|
name, err := windows.UTF16PtrFromString(mutexName)
|
|
if err != nil {
|
|
runtime.UnlockOSThread()
|
|
return nil, err
|
|
}
|
|
handle, err := windows.CreateMutex(nil, false, name)
|
|
if err != nil && !errors.Is(err, windows.ERROR_ALREADY_EXISTS) {
|
|
runtime.UnlockOSThread()
|
|
return nil, fmt.Errorf("create MSYS test mutex: %w", err)
|
|
}
|
|
event, err := windows.WaitForSingleObject(handle, windows.INFINITE)
|
|
if err != nil {
|
|
_ = windows.CloseHandle(handle)
|
|
runtime.UnlockOSThread()
|
|
return nil, fmt.Errorf("wait for MSYS test mutex: %w", err)
|
|
}
|
|
if event != windows.WAIT_OBJECT_0 && event != windows.WAIT_ABANDONED {
|
|
_ = windows.CloseHandle(handle)
|
|
runtime.UnlockOSThread()
|
|
return nil, fmt.Errorf("unexpected MSYS test mutex result: %#x", event)
|
|
}
|
|
return func() {
|
|
_ = windows.ReleaseMutex(handle)
|
|
_ = windows.CloseHandle(handle)
|
|
runtime.UnlockOSThread()
|
|
}, nil
|
|
}
|