Skip to content

Is modification of shared objects parallel-safe? #13

Description

@DarwinAwardWinner

The documentation mentions that the package allows reading and writing of shared memory, but it would be good to spell out whether or not it's safe for multiple R processes to write to the same object in parallel, and what the semantics of such operations would be. For example:

library(future)
library(future.apply)
library(future.callr)
plan(callr, workers = 20)
library(SharedObject)
library(assertthat)

## Parallel-safety test 1: add 1 to x 100 times, in parallel, in place
x <- share(0, minLength = 0, mustWork = TRUE, copyOnWrite = FALSE)
n <- 100
invisible(future_replicate(
    n,
    x[1] <- x[1] + 1,
    future.scheduling = FALSE
))
assert_that(x == n)
#> [1] TRUE

## Parallel-safety test 2: add 1 to x 100 times, in parallel, in
## place, but with an intermediate variable and a delay
x <- share(0, minLength = 0, mustWork = TRUE, copyOnWrite = FALSE)
n <- 100
invisible(future_replicate(
    n,
    {
        newval <- x[1] + 1
        Sys.sleep(0.1)
        x[1] <- newval
    },
    future.scheduling = FALSE
))
assert_that(x == n)
#> Error: x not equal to n

Created on 2023-08-08 with reprex v2.0.2

On the other hand, I would assume it should always be safe to write to different elements of the same vector in parallel, but maybe that's a bad assumption, e.g. if shared memory is written in "chunks".

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions