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 decrement_semaphore(wait = FALSE) will return FALSE whereas decrement_semaphore(wait = TRUE) will block until the semaphore is incremented by another process. If multiple processes are blocked, a single call to increment_semaphore() will only unblock one of the blocked processes.

It is possible to wait for a specific amount of time, for example, decrement_semaphore(wait = 10) 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

create_semaphore(id = NULL, value = 0, cleanup = TRUE)

increment_semaphore(id)

decrement_semaphore(id, wait = TRUE)

remove_semaphore(id)

Arguments

id

A semaphore identifier (string). create_semaphore() defaults to generating a random identifier. A custom id should be at most 251 characters and must not contain slashes (/).

value

The initial value of the semaphore.

cleanup

Remove the semaphore when R session exits.

wait

Maximum time (in seconds) to block the process while waiting for the semaphore. TRUE maps to 0; FALSE maps to Inf. Fractional seconds allowed (e.g. wait=0.001).

Value

  • create_semaphore() - The created semaphore's identifier (string), invisibly unless id=NULL.

  • increment_semaphore() - TRUE on success or FALSE on error, invisibly.

  • decrement_semaphore() - TRUE if the decrement was successful or FALSE otherwise, invisibly when wait=Inf.

  • remove_semaphore() - TRUE on success or FALSE on error.

Examples


    library(semaphore) 
    
    s <- create_semaphore()
    print(s)
#> [1] "SwlKLUUEdLieexomb92Q"
    
    increment_semaphore(s)
    decrement_semaphore(s, wait = FALSE)
#> [1] TRUE
    decrement_semaphore(s, wait = FALSE)
#> [1] FALSE
    
    remove_semaphore(s)