2
以下进程函数是我的工作函数。我需要让它访问一些创建/获取成本很高的类。在库中有没有针对线程局部变量的标准机制?或者我必须自己编写一个对象池管理器?scala并行集合:为工作线程设置线程局部变量的习惯方式
object Start extends App {
def progress {
val current = counter.getAndIncrement
if(current % 100 == 0) {
val perc = current.toFloat * 100/totalPosts
print(f"\r$perc%4.2f%%")
}
}
val lexicon = new Global()
def processTopic(forumId: Int, topicId: Int) {
val(topic, posts) = ProcessingQueries.getTopicAndPosts(forumId,topicId)
progress
}
val (fid, tl) = ProcessingQueries.getAllTopics("hon")
val totalPosts = tl.size
val counter = new AtomicInteger(0)
val par = tl.par
par.foreach { topic_id =>
processTopic(fid,topic_id)
}
}
你可以通过重写ThreadLocal上的initialValue来做到这一点。这样你就不需要执行get/set逻辑。 –