[R R R R R R R R R R R R R R R]

Thu 23 January 2014

[caption id="" align="alignright" width="350"]Spools of thread Spools of thread (Photo credit: Wikipedia)[/caption]

I wanted to use multithreading in R. I'm used to C pthread mechanism, but I want to use some R functions. This functions run independently on separate data, and treatments can take some time.

In short, what I wanted to do is computing 2 (or more) different things on a vector (R definition of vector), and reuse this vector later. Because this take some time and because i use a multicore computer, I want each of the 2 (or more) computing to be done on a different threads. The solution I test is the following:

  1. declare one function per specific task
  2. declare a switching function
    • take as input a number
    • for each number call one of the previously define function
  3. call the switching function in a `foreach <http://cran.r-project.org/web/packages/foreach/index.html>`__ loop
  4. write the results in an array-like object

A simple (running) code:

require(foreach)
require(doMC)                # any parallel backend
A <- numeric(10)             # store the results
i=list(c(1:5), c(6:10))      # index for each function

##
# all functions that will run in separate threads
# @param i vector of index
fun1 <- function(i){
    # whatever you want to do on that return the first part of your vector
    return (rep.int(max(i), length(i)))
}
fun2 <- function(i){
    # whatever you want to do on that return the rest of your vector
    return (cumsum(i))
}

##
# switching function
# @param selFun function number to select
switchingfun <- function(selFun=1,...){
    if(selFun==1) { fun1(...) }
    else          { fun2(...) }
}

foreach(sel = 1:2) %dopar%
{
    A[i[[sel]]] <- switchingfun(sel,i[[sel]])
}

A;

OK, there is no need to multithread this stuff. but imagine you have more function and a much bigger A vector.

Take care, i is a list, you should not omit the double square bracket.

(Non-)Related articles

Enhanced by Zemanta

Related articles (or not):

Category: programming Tagged: C CRAN Multithread POSIX Threads Programming R Threads