并行运行多个 shell 函数实例

金刚帕布达卡

我有一个 shell 脚本,如下所示。

#!/bin/bash

myfunc() {
   #do something (call a rest service)
   sleep 300
   status=$(get status of the operation performed above)
   while [ "$status" != "succeeded" ]; do
       #do something (call a rest service)
       sleep 300
       status=$(get status of the operation performed above)
   done
}

a=0

while [ $a -lt 1000 ]
do
   echo $a
   a=`expr $a + 1`
   myfunc
done

在最好的情况下,上面的脚本至少需要5*1000=5000几秒钟才能完成运行。

有没有办法使myfunc调用并行,以便我们可以让 while 循环产生myfunc??

注意:不知何故,这个脚本应该等到所有myfunc执行实例都完成。

安东尼奥·佩特里卡

我认为您可以按如下方式更新您的脚本:

#!/bin/bash

myfunc() {
   job_id=$1
   echo "Started job ${job_id}..."

   #do something (call a rest service)
   sleep 300
   status=$(get status of the operation performed above)
   while [ "$status" != "succeeded" ]; do
       #do something (call a rest service)
       sleep 300
       status=$(get status of the operation performed above)
   done

   echo "Terminated job ${job_id}."
}

a=0

while [ $a -lt 1000 ]
do
   echo $a
   a=(($a + 1))
   myfunc $a &
done

wait
echo "Parallel execution terminated."

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章