Simultaneous execution of several tasks in the background (parallel) in r

I want to run a program that takes a significant amount of time. I want to write a function that can work in parallel (I am a graphical user interface in windows). The function divides the task into n subtasks and performs the final coordinated task. I want to run the n task in parallel (at the same time in one program window), and then combine the outputs. The following example:

ptm <- proc.time()
j1 <- cov(mtcars[1:10,], use="complete.obs") # job 1
j2 <- cov(mtcars[11:20,], use="complete.obs") # job 2
j3 <- cov(mtcars[21:32,], use="complete.obs") # job 3
proc.time() - ptm

out <- list (j1 = j1, j2 = j2, j3 = j3) 

I know in unix "&" usually allows you to perform tasks in the background. Is there a similar path in R

+5
source share
2 answers

mclapply clusterApply . : R , ( wait, Unix, ).

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)
+7

plyr , snow. , . R 2.14 R parallel. plyr , parallel, , .

+1

All Articles