繁体   English   中英

foreach%dopar%写入同一文件

[英]foreach %dopar% write in a same file

我想在同一文件中并行写入,我测试了两个方法writeLinesink

path_file <- "path"
cl <- makeCluster(4)
registerDoParallel(cl)
#fileConn<-file(path_file, "w")
sink(path_file, append=TRUE)
foreach(i = 1:3) %dopar% 
{
  #writeLines(text = paste("hellow","world", i), con = fileConn, sep="\n")
  cat(paste("hellow","world", '\n'), file = path_file, append=TRUE)
}
sink()
#close(fileConn)
parallel::stopCluster(cl)

使用writeLine方法时出现错误:{:任务1失败-“连接错误”

使用接收器方法,我的文件结果为foreach [[]] NULL ,我不希望这样做。

hellow world 1 
hellow world 2 
hellow world 3 
[[1]]
NULL

[[2]]
NULL

[[3]]
NULL

另一种选择是将所有输出重定向到文件(这可能不是您想要的)

  library(doParallel)
  library(flock)
  path_file <- "path1.txt"
  cl <- makeCluster(4,outfile=path_file)
  registerDoParallel(cl)
  foreach(i = 1:10) %dopar% 
  {
    message <- paste("hello","world", i,"\n")
    print(message)
  }
  parallel::stopCluster(cl)

或者您可能希望每个元素都有一个文件,然后合并它们

  library(doParallel)
  library(flock)
  path_file <- "path"

  cl <- makeCluster(4)
  registerDoParallel(cl)
  foreach(i = 1:103, .export ="fileConn") %dopar% 
  {
    filename = paste0(path_file,i,".txt")
    message <- paste("hello","world", i,"\n")
    print(filename)
    cat(message, file = filename, append=TRUE)
    print(message)
  }

  parallel::stopCluster(cl)

  startfile= "full.txt"
  foreach(i = 1:103, .export ="fileConn") %do% 
  {
    filename = paste0(path_file,i,".txt")
    file.append(startfile,filename)
    file.remove(filename)
  }

当多个线程试图访问同一资源时,您需要小心。 为了同步对共享资源的访问,可以使用flock包设置互斥量。 (不确定以下原因为何不起作用,文件连接可能不是线程化的

看下面的代码示例

  library(doParallel)
  library(flock)
  path_file <- "path12.txt"
  fileConn<-file(path_file,open = "a")
  lock <-tempfile()

  cl <- makeCluster(4)
  registerDoParallel(cl)
  foreach(i = 1:103) %do% 
  {
    locked <- flock::lock(lock)  # Lock in order to use shared resources
    message <- paste("hello","world", i,"\n")
    cat(message, file = fileConn, append=TRUE)
    print(message)
    flock::unlock(locked)  # Release lock
    print(message)
  }

  close(fileConn)
  parallel::stopCluster(cl)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM