Skip to contents

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.

  • '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 semaphore object.

expr

Expression to evaluate if a semaphore is posted.

alt_expr

Expression to evaluate if timeout_ms is reached.

timeout_ms

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.

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, 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.

Examples


sem <- interprocess::semaphore()
print(sem)
#> <semaphore> "acHgb4k2HOc7WL"

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()