首页 > 解决方案 > 如何在多线程while循环之外扩展变量

问题描述

我正在编写一个包含多线程 while 循环的 shell 脚本。我的循环遍历数组的值。在循环中,我正在调用一个函数。在函数结束时,我将结果保存为字符串变量。我想在每次迭代时将此字符串变量添加到一个数组中,然后在 while 循环完成时能够检索此数组的内容。

根据我的理解,运行多线程 while 循环是导致 while 循环完成后数组为空的原因。每个线程都在自己的环境中运行,并且数组值不会扩展到该环境之外。如果可能的话,我希望能够在线程之外扩展这个数组值。目前我只是将字符串值写入临时文件,然后在 while 循环之后,读取临时文件的内容并将其保存为我的数组。这种方法有效,因为文件通常不是“太大”,但我想尽可能避免写入文件

我的代码 - doDeepLo​​okup 实际上是一个 API 调用,但为了论证,我们只说它在 while 循环的读取行前面附加了一些文本

#!/bin/bash
n=0
maxjobs=20

resultsArray=""
while IFS= read -r line
        do
        IPaddress="$(echo $line | sed 's/ /\n/g' | grep -E -o "([0-9]{1,3}[\.]){3}[0-9]{1,3}")"
        doDeepLookup "$line" "$IPaddress" &
        if(( $(($((++n)) % $maxjobs)) == 0 )) ; then
                wait
        fi
        done <<< "$(printf '%s\n' "${SomeOtherArray[@]}")"
        printf '%s\n' "${resultsArray[@]}" #Returns NULL

doDeepLookup() {
   results="$(echo "help me : $line")"
   resultsArray+=($results)
}

标签: bashshell

解决方案


感谢威廉

#!/bin/bash
n=0
maxjobs=20


WhileLoopFunction() {
    resultsArray=""
    while IFS= read -r line
        do
        IPaddress="$(echo $line | sed 's/ /\n/g' | grep -E -o "([0-9]{1,3}[\.]){3}[0-9]{1,3}")"
        doDeepLookup "$line" "$IPaddress" &
        if(( $(($((++n)) % $maxjobs)) == 0 )) ; then
                wait
        fi
        done <<< "$(printf '%s\n' "${SomeOtherArray[@]}")"
}

doDeepLookup() {
   results="$(echo "help me : $line")"
   echo $results
}

resultsArray=( $(WhileLoopFunction"${DeepArray[@]}") )
printf '%s\n' "${resultsArray[@]}"

推荐阅读