A semaphore is an integer that the operating system keeps track of. Any
process that knows the semaphore's identifier can increment or decrement its
value, though it cannot be decremented below zero.
When the semaphore is zero, calling $wait(timeout_ms = 0)
will
return FALSE
whereas $wait(timeout_ms = Inf)
will block until the
semaphore is incremented by another process. If multiple processes are
blocked, a single call to $post()
will only unblock one of the
blocked processes.
It is possible to wait for a specific amount of time, for example,
$wait(timeout_ms = 10000)
will wait for 10 seconds. If the
semaphore is incremented within those 10 seconds, the function will
immediately return TRUE
. Otherwise it will return FALSE
at the 10 second
mark.
semaphore(name = uid(), assert = NULL, value = 0, cleanup = FALSE, file = NULL)# S3 method for semaphore
with(data, expr, alt_expr = NULL, timeout_ms = Inf, ...)
semaphore()
returns a semaphore
object with the following methods:
$name
Returns the semaphore's name (scalar character).
$post()
Returns TRUE
if the increment was successful, or FALSE
on error.
$wait(timeout_ms = Inf)
Returns TRUE
if the decrement was successful, or FALSE
if the timeout is reached.
$remove()
Returns TRUE
on success, or FALSE
on error.
with()
returns eval(expr)
on success, or eval(alt_expr)
if the timeout is reached.
Unique ID. Alphanumeric, starting with a letter.
Apply an additional constraint.
'create'
- Error if the semaphore already exists.
'exists'
- Error if the semaphore doesn't exist.
NULL
- No constraint; create the semaphore if it doesn't exist.
The initial value of the semaphore.
Remove the semaphore when the R session exits. If FALSE
,
the semaphore will persist until $remove()
is called or the
operating system is restarted.
Use a hash of this file/directory path as the semaphore name. The file itself will not be read or modified, and does not need to exist.
A semaphore
object.
Expression to evaluate if a semaphore is posted.
Expression to evaluate if timeout_ms
is reached.
Maximum time (in milliseconds) to block the process
while waiting for the operation to succeed. Use 0
or Inf
to
return immediately or only when successful, respectively.
Not used.
sem <- interprocess::semaphore()
print(sem)
sem$post()
sem$wait(timeout_ms = 0)
sem$wait(timeout_ms = 0)
sem$post()
with(sem, 'success', 'timed out', timeout_ms = 0)
with(sem, 'success', 'timed out', timeout_ms = 0)
sem$remove()
Run the code above in your browser using DataLab