semaphore {interprocess} | R Documentation |
Increment and Decrement an Integer
Description
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.
Usage
semaphore(name = uid(), assert = NULL, value = 0, cleanup = FALSE, file = NULL)
## S3 method for class 'semaphore'
with(data, expr, alt_expr = NULL, timeout_ms = Inf, ...)
Arguments
name |
Unique ID. Alphanumeric, starting with a letter. |
assert |
Apply an additional constraint.
|
value |
The initial value of the semaphore. |
cleanup |
Remove the semaphore when the R session exits. If |
file |
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. |
data |
A |
expr |
Expression to evaluate if a semaphore is posted. |
alt_expr |
Expression to evaluate if |
timeout_ms |
Maximum time (in milliseconds) to block the process
while waiting for the operation to succeed. Use |
... |
Not used. |
Value
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, orFALSE
on error.
-
$wait(timeout_ms = Inf)
Returns
TRUE
if the decrement was successful, orFALSE
if the timeout is reached.
-
$remove()
Returns
TRUE
if the semaphore was successfully deleted from the operating system, orFALSE
on error.
with()
returns eval(expr)
on success, or eval(alt_expr)
if the timeout is reached.
See Also
Other shared objects:
msg_queue()
,
mutex()
Examples
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()