使用Jenkins Pipeline脚本,从并行步骤访问全局变量是否安全



在编写Jenkins Pipeline脚本时,从并行步骤访问变量是否安全?文件对此并不清楚。

例如,此流水线代码修改来自并行分支的公共计数器和队列:

def donecount = 0;
def work = [6,5,4,3,2,1,0]
def branches = [:]
for (int i = 0; i < 3; i++) {
    branches["worker-${i}"] = {
        while (true) {
            def item = null
            try {
                item = work.remove(0)
            } catch (java.lang.IndexOutOfBoundsException e) {
                break
            }
            echo "Working for ${item} seconds"
            sleep time:item
            donecount += 1
        }
    }
}
branches.failFast = true
parallel branches
echo "Completed ${donecount} tasks"

在当前的实现中,这可能是安全的,因为管道执行使用协作多任务(也称为"绿色线程")。但我不确定,例如,+=是否是Groovy中的原子操作,其粒度在这里很重要。更安全的做法是使用标准的Java并发实用程序:ConcurrentLinkedQueueAtomicInteger等。

最新更新