mutex | R Documentation |
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.
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, ...)
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. |
The operating system ensures that mutex locks are released when a process exits.
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, or FALSE
if the timeout is reached.
$unlock(warn = TRUE)
Returns TRUE
if successful, or FALSE
(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, or FALSE
on error.
with()
returns eval(expr)
if the lock was acquired, or eval(alt_expr)
if the timeout is reached.
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.
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.
Other shared objects:
msg_queue()
,
semaphore()
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)
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.