0

我编写了一个小方法来执行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变量。

获得此线程安全的正确方法是什么?

4

1 回答 1

1

更改eachParallel闭包参数中的赋值语句,如下所示:

        def (exit, out, err, cmd) = git("clone ${cloneUrl} ${cloneDir}")

这将使变量成为闭包的局部变量,从而使它们成为线程安全的。该git()方法很好。

于 2016-12-02T20:55:03.643 回答