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.
Arguments
- name
Unique ID. Alphanumeric, starting with a letter.
- assert
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.
- value
The initial value of the semaphore.
- cleanup
Remove the semaphore when the R session exits. If
FALSE, the semaphore will persist until$remove()is called or the operating system is restarted.- 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
semaphoreobject.- expr
Expression to evaluate if a semaphore is posted.
- alt_expr
Expression to evaluate if
timeout_msis reached.- timeout_ms
Maximum time (in milliseconds) to block the process while waiting for the operation to succeed. Use
0orInfto return immediately or only when successful, respectively.- ...
Not used.
Value
semaphore() returns a semaphore object with the following methods:
$nameReturns the semaphore's name (scalar character).
$post()Returns
TRUEif the increment was successful, orFALSEon error.
$wait(timeout_ms = Inf)Returns
TRUEif the decrement was successful, orFALSEif the timeout is reached.
$remove()Returns
TRUEif the semaphore was successfully deleted from the operating system, orFALSEon error.
with() returns eval(expr) on success, or eval(alt_expr) if the timeout is reached.
Examples
sem <- interprocess::semaphore()
print(sem)
#> <semaphore> "Ab3qdfGwf22"
sem$post()
sem$wait(timeout_ms = 0)
#> [1] TRUE
sem$wait(timeout_ms = 0)
#> [1] FALSE
sem$post()
with(sem, 'success', 'timed out', timeout_ms = 0)
#> [1] "success"
with(sem, 'success', 'timed out', timeout_ms = 0)
#> [1] "timed out"
sem$remove()
