bash - 如何在多线程while循环之外扩展变量
问题描述
我正在编写一个包含多线程 while 循环的 shell 脚本。我的循环遍历数组的值。在循环中,我正在调用一个函数。在函数结束时,我将结果保存为字符串变量。我想在每次迭代时将此字符串变量添加到一个数组中,然后在 while 循环完成时能够检索此数组的内容。
根据我的理解,运行多线程 while 循环是导致 while 循环完成后数组为空的原因。每个线程都在自己的环境中运行,并且数组值不会扩展到该环境之外。如果可能的话,我希望能够在线程之外扩展这个数组值。目前我只是将字符串值写入临时文件,然后在 while 循环之后,读取临时文件的内容并将其保存为我的数组。这种方法有效,因为文件通常不是“太大”,但我想尽可能避免写入文件
我的代码 - doDeepLookup 实际上是一个 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)
}
解决方案
感谢威廉
#!/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[@]}"
推荐阅读
- entity-framework - 存储过程返回 0
- firebase - 通过 Cloud Function 从 Firebase 实时数据库获取数据
- wolfram-mathematica - 多项式因式分解
- java - AspectJ Weaver & java 模块系统(spring + gradle),编译问题
- python - 就地修改大于内存的 Dask 数组
- java - 如何从 AsyncTask 中的数据库类中获取对象?
- node.js - 如何在常规节点应用程序旁边运行strapi
- eclipse - 如何配置代码辅助,导入语句无通配符
- c# - C# - 从动态方法调用具有“参数字符串 []”的委托
- java - 如何从 Java 中的子类调用 int 或 string