File Lock Guard Critical Section
Use file locks for cross-process critical sections with flock in Go applications safely.
Code
package main
import ("os";"syscall";"fmt")
func withFileLock(path string, fn func() error) error {
f, err := os.Create(path)
if err != nil { return err }
defer f.Close()
if err := syscall.Flock(int(f.Fd()), syscall.LOCK_EX); err != nil { return err }
defer syscall.Flock(int(f.Fd()), syscall.LOCK_UN)
return fn()
}
func main() {
withFileLock("/tmp/app.lock", func() error {
fmt.Println("critical section")
return nil
})
}Report a problem with this exampleOpens a pre-filled issue on GitHub.