I have a a bunch of computation that needs to be done in parallel. In this computation the database is accessed through one global channel. So it is something like this:
library(doMC)
registerDoMC(2)
channel <<- connect_to_database()
results <- foreach(i=indexes) %dopar% {
data <- get_data_from_db(channel)
result <- do_computations(data)
}
But them I get this error:
task 1 failed - "cannot open the connection"
The reason, very probably is because the threads are accessing the channel simultaneously. Is there a way to put a mutex around the get_data_from_db? Or create more connections and check if there is a free one before accessing it? Any suggestions?
Thanks a lot!
---------------Edit-------------- Now I am creating one connection for each index. But I'm getting this error now:
task 1 failed - "expired MySQLConnection"
library(doMC)
registerDoMC(2)
channel<<-list()
for(i=indexes){
channel[[i]] <-connect_to_database(...)
}
results <- foreach(i=indexes) %dopar% {
data <- get_data_from_db(channel[[ind]])
result <- do_computations(data)
}