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.

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.

value

The initial value of the semaphore.

cleanup

Remove the semaphore when R session exits.

wait

If TRUE, blocks until semaphore is greater than zero.

Value

  • create_semaphore() - The created semaphore's identifier (string), invisibly when semaphore is non-NULL.

  • increment_semaphore() - TRUE, invisibly.

  • decrement_semaphore(wait = TRUE) - TRUE, invisibly.

  • decrement_semaphore(wait = FALSE) - TRUE if the decrement was successful; FALSE otherwise.

  • remove_semaphore() - TRUE on success; 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)
#> [1] TRUE