您可以使用mclapply
或clusterApply
并行启动多个功能。它们实际上并不在后台:R 将等到它们全部完成(就像您wait
在 Unix shell 中使用 , 在后台启动进程之后一样)。
library(parallel)
tasks <- list(
job1 = function() cov(mtcars[1:10,], use="complete.obs"),
job2 = function() cov(mtcars[11:20,], use="complete.obs"),
job3 = function() cov(mtcars[21:32,], use="complete.obs"),
# To check that the computations are indeed running in parallel.
job4 = function() for (i in 1:5) { cat("4"); Sys.sleep(1) },
job5 = function() for (i in 1:5) { cat("5"); Sys.sleep(1) },
job6 = function() for (i in 1:5) { cat("6"); Sys.sleep(1) }
)
# Using fork()
out <- mclapply(
tasks,
function(f) f(),
mc.cores = length(tasks)
)
# Equivalently: create a cluster and destroy it.
# (This may work on Windows as well.)
cl <- makeCluster( length(tasks) )
out <- clusterApply(
cl,
tasks,
function(f) f()
)
stopCluster(cl)