Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
833 views
in Technique[技术] by (71.8m points)

multithreading - Run asynchronous function in R

I have the following code:

myfun <- function() {
  fun2()

  return(1+1)
}

I want fun2() is invoked and then moved to the next lines without waiting for the result. Function fun2 does not return anything and I don't care when it finishes, I just need to launch it. What is the best way to achieve it? Parallel process, multithreading, async call? Any code samples are appreciated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The future package (I'm the author) provides this:

library("future")
plan(multiprocess)

myfun <- function() {
  future(fun2())

  return(1+1)
}

Unless fun2() is function used purely for its side effects, you typically want to retrieve the value of that future expression, which you do as:

f <- future(fun2())
y <- fun3()
v <- value(f)
z <- v + y

An alternative is to use the %<-% operator as in:

v %<-% fun2()
y <- fun3()
z <- v + y

FYI, if you use

plan(cluster, workers = c("n1", "n3", "remote.server.org"))

then the future expression is resolved on one of those machines. Using

plan(future.BatchJobs::batchjobs_slurm)

will cause it to be resolved via a Slurm job scheduler queue.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...