我编写了一个小方法来执行git
命令行工具并捕获其输出:
def git(String command) {
command = "git ${command}"
def outputStream = new StringBuilder()
def errorStream = new StringBuilder()
def process = command.execute()
process.waitForProcessOutput(outputStream, errorStream)
return [process.exitValue(), outputStream, errorStream, command]
}
我将它与 GPars 一起使用以同时克隆多个存储库,例如
GParsPool.withPool(10) {
repos.eachParallel { cloneUrl, cloneDir->
(exit, out, err, cmd) = git("clone ${cloneUrl} ${cloneDir}")
if (exit != 0) {
println "Error: ${cmd} failed with '${errorStream}'."
}
}
}
但是,我相信我的git
方法不是线程安全的:例如,在第一个线程到达方法的第五行command
之前,第二个线程可以在方法的第一行进行修改。command.execute()
我可以通过制作整个git
方法来解决这个问题synchronized
,但这会破坏在不同线程中运行它的目的,因为我希望克隆并行发生。
所以我想像做部分同步
def git(String command) {
def outputStream
def errorStream
def process
synchronized {
command = "git ${command}"
outputStream = new StringBuilder()
errorStream = new StringBuilder()
process = command.execute()
}
process.waitForProcessOutput(outputStream, errorStream)
return [process.exitValue(), outputStream, errorStream, command]
}
但我想这也不安全,因为线程二waitForProcessOutput()
可能比线程一更早返回,从而搞砸了outputStream
/errorStream
变量。
获得此线程安全的正确方法是什么?