package proc import ( "context" "errors" "os" "syscall" "time" ) // Lock is held by one holder at a time: across this process's // goroutines (a channel) and the runner's processes (an flock on Path; // "" keeps it within this process). type Lock struct { ch chan struct{} path string f *os.File } // NewLock is a lock on path. func NewLock(path string) *Lock { return &Lock{ch: make(chan struct{}, 1), path: path} } // Acquire waits for the lock until ctx ends. func (l *Lock) Acquire(ctx context.Context) error { select { case l.ch <- struct{}{}: case <-ctx.Done(): return ctx.Err() } if l.path == "" { return nil } f, err := os.OpenFile(l.path, os.O_CREATE|os.O_RDWR, 0600) if err != nil { <-l.ch return err } for { err := syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB) if err == nil { l.f = f return nil } if !errors.Is(err, syscall.EWOULDBLOCK) { f.Close() <-l.ch return err } select { case <-ctx.Done(): f.Close() <-l.ch return ctx.Err() case <-time.After(250 * time.Millisecond): } } } // TryAcquire takes the lock only if it is free now. func (l *Lock) TryAcquire() bool { select { case l.ch <- struct{}{}: default: return false } if l.path == "" { return true } f, err := os.OpenFile(l.path, os.O_CREATE|os.O_RDWR, 0600) if err == nil { if err = syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB); err == nil { l.f = f return true } f.Close() } <-l.ch return false } // Release gives the lock back. func (l *Lock) Release() { if l.f != nil { _ = syscall.Flock(int(l.f.Fd()), syscall.LOCK_UN) l.f.Close() l.f = nil } <-l.ch }