25 lines
481 B
Go
25 lines
481 B
Go
package file
|
|
|
|
import "sync"
|
|
|
|
// FileLocks provides per-filename mutexes to handle concurrent writes safely.
|
|
type FileLocks struct {
|
|
mu sync.Mutex
|
|
locks map[string]*sync.Mutex
|
|
}
|
|
|
|
func NewFileLocks() *FileLocks {
|
|
return &FileLocks{locks: make(map[string]*sync.Mutex)}
|
|
}
|
|
|
|
func (f *FileLocks) Lock(filename string) func() {
|
|
f.mu.Lock()
|
|
m, ok := f.locks[filename]
|
|
if !ok {
|
|
m = &sync.Mutex{}
|
|
f.locks[filename] = m
|
|
}
|
|
f.mu.Unlock()
|
|
m.Lock()
|
|
return func() { m.Unlock() }
|
|
}
|