Search code examples
rblocking

Blocking and waiting in R


It would be extremely useful to me to be able to create a function in R that could block until a resource is defined or is given the appropriate value. I know that R is single-threaded, but I had hoped that mc would be able to help. However,

library(parallel)
f = function() {
  while(!exists('a')) Sys.sleep(1);
  print('success!')
}
d = mcparallel(f())
a = 1
mccollect(d)

hangs indefinitely. Is there any effective workaround, or will I have to look into radically different patterns/a different language to achieve something of the sort?


Solution

  • I didn't even know it was possible to fork processes like that. After playing around for a bit, I found the sendChildStdin function, which you should check out. It is at least one way to signal the child processes. Here is an example:

    f<- function () {
      message<-scan(n = 1, quiet = TRUE, what='character')
      return(message)
    }
    p  <- mcparallel(f())
    a <- 1
    # The message shouldn't contain spaces and should end with a newline.
    parallel:::sendChildStdin(p, "created\n") 
    mccollect(p)[[1]]
    [1] "created"
    

    Don't get me wrong; R is probably not the language you want if you are going to get into the stuff heavily, but it might work for light applications.


    I had tested the code before in RStudio, and although it appeared to work, it was failing in a way that was indistinguishable from success. Anyway, it essentially doesn't wait for the scan process. For example, this should never complete, but it does (in RStudio only)

    f<- function () {
      message<-scan(n = 1, quiet = TRUE, what='character')
      return(message)
    }
    p  <- mcparallel(f())
    # parallel:::sendChildStdin(p, "created\n")
    mccollect(p)[[1]]
    # character(0)