Modify variables outside function using mclapply

885 Views Asked by At

It is easy to modify variables outside a function using assign() or <<-, even if the function is called with lapply(). But these tricks seem not working while calling function with mclapply(), the parallel version of lapply() in package multicore:

require(multicore)
f <- function(i) {
    x[i] <- x[i] + 1
    y[i] <<- y[i] + 1
}
x <- y <- 1:10
invisible(lapply(1:5, f))
x #  1  2  3  4  5  6  7  8  9 10, not changed
y #  2  3  4  5  6  6  7  8  9 10, variables 1 to 5 changed

# Now running with mclapply
x <- y <- 1:10
invisible(mclapply(1:5, f))
x # 1  2  3  4  5  6  7  8  9 10, not changed
y # 1  2  3  4  5  6  7  8  9 10, not changed again!

How to do the same task - modifying variables outside the function - while calling function by mclapply()?

I know this should be used with care, because the parallel running functions may try to modify the same variable that can cause severe synchronization errors, however it is helpful in some cases.

0

There are 0 best solutions below