Skip to content

Commit

Permalink
Added windows version of TryLock
Browse files Browse the repository at this point in the history
moved AlreadyLocked to general file so it's the same instance for all
  • Loading branch information
femaref committed Oct 8, 2019
1 parent 4582108 commit f02b7bf
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 3 deletions.
5 changes: 5 additions & 0 deletions filemutex.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
package filemutex

import "errors"

var AlreadyLocked = errors.New("lock already acquired")
2 changes: 0 additions & 2 deletions filemutex_flock.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,6 @@ func (m *FileMutex) Lock() error {
return nil
}

var AlreadyLocked = errors.New("lock already acquired")

func (m *FileMutex) TryLock() error {
if err := syscall.Flock(m.fd, syscall.LOCK_EX|syscall.LOCK_NB); err != nil {
if errno, ok := err.(syscall.Errno); ok {
Expand Down
16 changes: 15 additions & 1 deletion filemutex_windows.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@ var (
)

const (
lockfileExclusiveLock = 2
lockfileFailImmediately = 1
lockfileExclusiveLock = 2
)

func lockFileEx(h syscall.Handle, flags, reserved, locklow, lockhigh uint32, ol *syscall.Overlapped) (err error) {
Expand Down Expand Up @@ -58,6 +59,19 @@ func New(filename string) (*FileMutex, error) {
return &FileMutex{fd: fd}, nil
}

func (m *FileMutex) TryLock() error {
var ol syscall.Overlapped
if err := lockFileEx(m.fd, lockfileFailImmediately|lockfileExclusiveLock, 0, 1, 0, &ol); err != nil {
if errno, ok := err.(syscall.Errno); ok {
if errno == syscall.Errno(0x21) {
return AlreadyLocked
}
}
return err
}
return nil
}

func (m *FileMutex) Lock() error {
var ol syscall.Overlapped
if err := lockFileEx(m.fd, lockfileExclusiveLock, 0, 1, 0, &ol); err != nil {
Expand Down

0 comments on commit f02b7bf

Please sign in to comment.