Lock blocks until it acquires an exclusive lock on the given path, retrying TryLock with small sleep gaps while another process holds the lock. It stops waiting when ctx is done and returns ErrTimeout in that case, so a stuck or long-held lock cannot block the caller indefinitely. Any error other th
(ctx context.Context, path string)
| 28 | // contention is returned immediately. On success it returns the locked file and |
| 29 | // an unlock function, with the same semantics as TryLock. |
| 30 | func Lock(ctx context.Context, path string) (f *os.File, unlock func(), err error) { |
| 31 | for { |
| 32 | f, unlock, err = TryLock(path) |
| 33 | if err == nil { |
| 34 | return f, unlock, nil |
| 35 | } else if !errors.Is(err, ErrLocked) { |
| 36 | return nil, nil, err |
| 37 | } |
| 38 | |
| 39 | select { |
| 40 | case <-ctx.Done(): |
| 41 | return nil, nil, ErrTimeout |
| 42 | case <-time.After(lockRetryInterval): |
| 43 | } |
| 44 | } |
| 45 | } |