问题
I'm trying to understand the forking system implemented by R's multicore package. The package example is:
p <- fork()
if (inherits(p, "masterProcess")) {
cat("I’m a child! ", Sys.getpid(), "\n")
exit(,"I was a child")
}
cat("I’m the master\n")
unserialize(readChildren(1.5))
but it doesn't seem to work when pasted in the R interactive console. Does anyone have an example of using fork() with R's multicore or parallel packages?
回答1:
The fork example in the multicore package 'works for me' ; try example(fork). fork is only supported on non-Windows systems.
I think the equivalent functions in parallel are mcparallel() to fork and then evaluate an expression, and mcollect() to retrieve the result when done. So
id = mcparallel({ Sys.sleep(5); TRUE })
returns immediately but the process is running, and
mccollect(id)
will return TRUE after 5 seconds. There is no communication other than the collection between the forked and master process; it would be interesting and not too challenging to implement two-way communication using, e.g., sockets.
来源:https://stackoverflow.com/questions/23045288/how-to-fork-processes-in-r