mutex {interprocess} | R Documentation |
Shared and Exclusive Locks
Description
Mutually exclusive (mutex) locks are used to control access to shared
resources.
An exclusive lock grants permission to one process at a time, for
example to update the contents of a database file. While an exclusive lock
is active, no other exclusive or shared locks will be granted.
Multiple shared locks can be held by different processes at the same
time, for example to read a database file. While a shared lock is active, no
exclusive locks will be granted.
Usage
mutex(name = uid(), assert = NULL, cleanup = FALSE, file = NULL)
## S3 method for class 'mutex'
with(data, expr, alt_expr = NULL, shared = FALSE, timeout_ms = Inf, ...)
Arguments
name |
Unique ID. Alphanumeric, starting with a letter. |
assert |
Apply an additional constraint.
|
cleanup |
Remove the mutex when the R session exits. If |
file |
Use a hash of this file/directory path as the mutex name. The file itself will not be read or modified, and does not need to exist. |
data |
A |
expr |
Expression to evaluate if the mutex is acquired. |
alt_expr |
Expression to evaluate if |
shared |
If |
timeout_ms |
Maximum time (in milliseconds) to block the process
while waiting for the operation to succeed. Use |
... |
Not used. |
Details
The operating system ensures that mutex locks are released when a process exits.
Value
mutex()
returns a mutex
object with the following methods:
-
$name
Returns the mutex's name (scalar character).
-
$lock(shared = FALSE, timeout_ms = Inf)
Returns
TRUE
if the lock is acquired, orFALSE
if the timeout is reached.
-
$unlock(warn = TRUE)
Returns
TRUE
if successful, orFALSE
(with optional warning) if the mutex wasn't locked by this process.
-
$remove()
Returns
TRUE
if the mutex was successfully deleted from the operating system, orFALSE
on error.
with()
returns eval(expr)
if the lock was acquired, or eval(alt_expr)
if the timeout is reached.
Error Handling
The with()
wrapper automatically unlocks the mutex if an error stops
evaluation of expr
. If you are directly calling lock()
, be sure that
unlock()
is registered with error handlers or added to on.exit()
.
Otherwise, the lock will persist until the process terminates.
Duplicate Mutexes
Mutex locks are per-process. If a process already has a lock, it can not attempt to acquire a second lock on the same mutex.
See Also
Other shared objects:
msg_queue()
,
semaphore()
Examples
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)