tmp <- tempfile()
mut <- interprocess::mutex(file = tmp)
print(mut)
# Exclusive lock to write the file
with(mut, writeLines('some data', tmp))
# Use a shared lock to read the file
with(mut,
shared = TRUE,
timeout_ms = 0,
expr = readLines(tmp),
alt_expr = warning('Mutex was locked. Giving up.') )
# Directly lock/unlock with safeguards
if (mut$lock(timeout_ms = 0)) {
local({
on.exit(mut$unlock())
writeLines('more data', tmp)
})
} else {
warning('Mutex was locked. Giving up.')
}
mut$remove()
unlink(tmp)
Run the code above in your browser using DataLab