6

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?

1
  • Different process do not share their memory, so your child process cannot detect the creation of variable a in main process.
    – wush978
    Commented Feb 6, 2013 at 2:31

3 Answers 3

7

Another hack, with little to recommend it, is to adapt the example at the bottom of ?socketConnection communicating between the two processes using sockets. We make the forked process the server (the server has to be started first, so can't be the interactive process) and send it on its way...

f <- function() {
    system.time({
        con1 <- socketConnection(port = 6011, server = TRUE, open="r")
        while (isIncomplete(con1))
            readLines(con1)
        close(con1)
    })
}     
d <- mcparallel(f())

Then we communicate with it, once only, and collect the results

con2 <- socketConnection(Sys.info()["nodename"], port = 6011)
writeLines("ok", con2)
close(con2)
mccollect(d)

which shows me that the forked process waited for a second and a half while I executed subsequent commands

> mccollect(d)
$`28975`
   user  system elapsed 
  0.000   0.000   1.515 

This would have a more legitimate feel if the processes were separate rather than forked, as in an MPI job where one could use the Rmpi package to communicate between nodes.

1
  • Is there any way to have the server actively listen for commands? What I initially tried to do was: con1 <- socketConnection(port = 6011, server = TRUE, open="r"); i = 0; while (i==0) { if(a <- readLines(con1)) eval(parse(text=a)) }; close(con1); but this seemed to result in a deadlock as soon as I created a client connection.
    – tresbot
    Commented Feb 13, 2013 at 0:23
5

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)
3
  • I'm not sure why, but this isn't working for me; tried including what='character' in scan() and sending a string without spaces in case those were causing problems with scan, but to no avail. Any thoughts on why that could be? All I can think is version; I'm running R-2.15.1 on an x64 system.
    – tresbot
    Commented Feb 6, 2013 at 12:02
  • @tresbot I don't get it. The code only works in RStudio Server for me. I can't get it to work anywhere else.
    – nograpes
    Commented Feb 6, 2013 at 15:11
  • @tresbot Okay, I got it. The code was essentially failing before. As you pointed out, you need what='character' and you need no spaces in the message, but you also need to end with a \n.
    – nograpes
    Commented Feb 6, 2013 at 15:43
2

I don't know of a way using parallel, but the tcltk utilities run in a way that appears parallel or background to the regular R event loop. You can use the tclTaskSchedule function from the tcltk2 package to do something like your above loop:

library(tcltk)
library(tcltk2)
tclTaskSchedule(1000, if( exists('a') ) { 
    tclTaskChange('WaitForA', redo=FALSE)
    cat('Success!\n\n')
    }, id='WaitForA',  redo=TRUE )

Now you can do other things in R (assuming a does not exist yet) and in the background the above will check for a about every 1 second. Once you create a (or within about a second of that) then 'Success!' will be printed to the screen (and it will stop checking).

Note that this is a replacement for using parallel. Apparently the tcltk and parallel packages don't play nicely together (it looks like this has been fixed in R devel and patched so this may work with parallel after R version 2.15.3). So be careful using this if you are also using the parallel package for other things. If parallel was just an option that you were trying and you are not using it for other things then this method should work fine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.