[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 (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:
- declare one function per specific task
- declare a switching function
- take as input a number
- for each number call one of the previously define function
- call the switching function in a `foreach <http://cran.r-project.org/web/packages/foreach/index.html>`__ loop
- 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
- C++ class for pthread conditional variable (cppcodetips.wordpress.com)
- Computer Networks-Socket Programming- C (vnpshares.wordpress.com)
- Quick guide to parallel R with snow (r-bloggers.com)
- Evaluate args of a function call and convert the call to a character vector in R (stackoverflow.com)
- Difference between multitasking, multithreading and multiprogramming (cs.stackexchange.com)
- POSIX thread (pthread) libraries (yolinux.com)
- Manipulation des threads (http://fr.openclassrooms.com)
Category: programming Tagged: C CRAN Multithread POSIX Threads Programming R Threads