从并行包获取线程ID

时间:2017-03-03 17:00:00

标签: r parallel-processing

我有一个简单的共享内存代码helloworld.R代码:

library(parallel)
nCores <- detectCores()
v<-character(length=nCores)
tid<-someFuncToGetThreadID()     # <---What function to use here?
v<-mclapply(v,function(x) x=sprintf("Hello World from thread : %i",tid))

如何获取每个线程的线程ID(tid)?

2 个答案:

答案 0 :(得分:1)

它们是分叉的进程而不是线程。您可以使用Sys.getpid()来获取进程ID。

答案 1 :(得分:0)

您可以尝试自己分配ID。

clusterApply(cl, 1:cluster_num, function(x){
    tid <<- x
})

例如,

library(parallel)
ncluster <- 5
cl <- makeCluster(ncluster)
clusterApply(cl,1:ncluster, function(x){
    tid <<- x
})
v<-clusterCall(cl, function(){sprintf("Hello World from thread :%d",tid)})
stopCluster(cl)