I am trying to implement a global counter in a library. This counter
resides in an environment local to that package, and is incremented by
calling a function within this package.
Problems arise when I use parallelization. I protected the increment
operation with a lock so that this operation effectively should be
atomic. However, the environment local to the package seems not to be
shared among the threads that use the functions in that package (not in
the sense that a change would be visible in the other threads).
How is such a global counter best implemented?
Here is a basic sketch of what I tried:
library(parallel)
library(flock)
## begin of code in package
tmp <- tempfile()
.localstuff <- new.env()
.localstuff$N <- 0
.localstuff$tmp <- tempfile()
incr <- function()
{
h <- lock(.localstuff$tmp)
.localstuff$N <- .localstuff$N + 1
unlock(h)
}
## end code in library
invisible(mclapply(1:10, function(i) incr()))
cat("N =", .localstuff$N)
______________________________________________
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.