Reputation: 153
I am trying to do parallel processing in R shiny, the parallel task which I want to do is a call to python script. However it does not work and not able to fetch the result back from python to R. Below is the sample R shiny and Python code. App.R
library(shiny)
library(reticulate)
library(doParallel)
library(foreach)
ui <- fluidPage(
# Application title
titlePanel("Sample Program"),
mainPanel(
uiOutput("txtValue")
)
)
server <- function(input, output) {
source_python("../../PythonCode/Multiprocessing/multip.py")
cl <- makeCluster(detectCores(), type='PSOCK')
registerDoParallel(cl)
result <- foreach(i=1:5) %dopar% fsq(i)
stopCluster(cl)
output$txtValue <- renderUI({
result
})
}
shinyApp(ui = ui, server = server)
Python Code (multip.py)
def fsq(x):
return x**2
Upvotes: 2
Views: 1821
Reputation: 26823
The error message is independent of shiny
:
library(reticulate)
library(doParallel)
library(foreach)
library(parallel)
source_python("multip.py")
cl <- makeCluster(detectCores(), type = 'PSOCK')
registerDoParallel(cl)
# throws: Error in unserialize(socklist[[n]]) : error reading from connection
foreach(i = 1:5) %dopar% fsq(i)
stopCluster(cl)
I interpret this such that one cannot serialize a Python function as one can serialize a R function. A simple workaround is to use source_python
within the loop:
library(doParallel)
library(foreach)
library(parallel)
cl <- makeCluster(detectCores(), type = 'PSOCK')
registerDoParallel(cl)
foreach(i = 1:5) %dopar% {
reticulate::source_python("multip.py")
fsq(i)
}
stopCluster(cl)
Upvotes: 3