Cross-process file locking is essential for ensuring that multiple processes don't interfere with each other while accessing the same file. In .NET, this can be achieved using File.Open with FileShare.None. How can we achieve exclusive file access in Go?
The fslock package provides a cross-platform solution for file locking. It utilizes LockFileEx on Windows and flock on *nix systems.
To use fslock, begin by creating a new lock object:
lock := fslock.New("file.txt")
This command creates the lock file if it doesn't already exist.
To acquire an exclusive lock on the file, use the Lock method:
lockErr := lock.Lock() if lockErr != nil { // Handle error }
Alternatively, you can use LockWithTimeout to wait for the lock within a specified duration:
lockErr := lock.LockWithTimeout(10 * time.Second) if lockErr != nil { // Handle timeout }
When you're done with the file, release the lock using Unlock:
lock.Unlock()
The following code snippet demonstrates how to use the fslock package to lock a file for exclusive access:
package main import ( "time" "fmt" "github.com/juju/fslock" ) func main() { lock := fslock.New("file.txt") lockErr := lock.TryLock() if lockErr != nil { fmt.Println("Failed to acquire lock:", lockErr) return } fmt.Println("Got the lock") time.Sleep(1 * time.Minute) // Release the lock lock.Unlock() }
The above is the detailed content of How Can I Achieve Exclusive File Locking in Go?. For more information, please follow other related articles on the PHP Chinese website!