Lock a file between processes
Let one run of a program at a time do its work, such as a backup script that cron starts again while its last run is still going.
- Pick a lock file that every run names the same way, such as a file under Os.cacheDir. The directory must exist; the file need not.
- Call File.tryLock on it. It returns
nullwhen another run holds the lock. - Exit when the result is
null. - Close the handle with
deferright after you get it. Closing it releases the lock.
Skip the run when another one holds the lock
let path = Path.join([try Os.cacheDir(), "backup.lock"])
let lock = try File.tryLock(path)
if lock == null {
eprintln("backup: already running")
Os.exit(1)
}
defer { lock.close() }
println("backing up")Here another handle holds the lock file, so the script writes backup: already running to standard error and exits with status 1. When no one holds the lock, it prints backing up and releases the lock as it ends.
The operating system releases the lock when the process ends, however it ends, a crash and kill -9 included. A lock is never left stale, as a pid file is, so you never delete the lock file by hand. Leave the file in place: the next run locks it again.
Wait for the lock
To queue behind the run that holds the lock instead of giving up, call File.lock. It waits until the lock is free. Give it a context from Context.new to limit the wait:
let lock = try (File.lock("deploy.lock", ctx: Context.new(30s)) | Result.wrapErr("wait for deploy.lock"))
defer { lock.close() }
println("deploying")deployingWhen the context ends first, File.lock returns an Err with the context's reason, and try ends the script with status 1:
let lock = try (File.lock("deploy.lock", ctx: Context.new(100ms)) | Result.wrapErr("wait for deploy.lock"))
defer { lock.close() }
println("deploying")The script writes wait for deploy.lock: timeout to standard error.
Guard another file
The lock keeps out only programs that lock too, so every program that changes the data takes the same lock first. Keep the data in its own file and lock a file next to it. Read, change, and write the data while you hold the lock:
func addVisit(path: string): Result[void, Error] {
let lock = try File.lock("${path}.lock")
defer { lock.close() }
let count = if File.exists(path) { (try File.read(path)).trim().toInt() ?? 0 } else { 0 }
File.write(path, "${count + 1}\n")
}
let results = Parallel.map(Array.range(0, 20), func(i: int, ctx: Context): Result[void, Error] {
addVisit("visits.txt")
}, limit: 8) ?? return Result.fail("cancelled")
for r in results {
try r
}
print(try File.read("visits.txt"))20The lock belongs to the handle, not to the process, so it orders goroutines of one program as it orders processes: here Parallel.map runs addVisit eight at a time, and no visit is lost.
Things to know
- There is no unlock. Closing the handle is the one release.
- On Unix the lock is advisory: a program that writes the file without locking it is not stopped. On Windows other processes cannot read or write the file while the lock is held.
- To lock again right after a close, call
File.lock, which waits, notFile.tryLock: a child process that another goroutine starts at that moment can hold the lock a moment after the close. - Whether the lock is held is what
File.tryLockanswers, not what the file holds. Do not keep a pid in it: the lock never truncates the file, so a shorter pid leaves the tail of a longer one.
See also
File.tryLock · File.lock · File.close · Context.new · Result.wrapErr · Os.exit · Os.cacheDir · Path.join · Parallel.map · File.read · File.write · File.exists
