首页 > 解决方案 > 并行运行 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 "Starting myfunc with process : $a"
   a=`expr $a + 1`
   myfunc
   echo "Finished myfunc with process : $a"
done

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

有没有办法使myfunc调用并行,以便我们可以让 while 循环产生多个正在运行的myfunc??

除此之外,我希望满足以下条件。

  1. 该脚本应该等到所有myfunc执行实例都完成。
  2. 上面的输出应该如下所示(它应该保留回显顺序)。
    Starting myfunc with process : x
    Finished myfunc with process : x
    Starting myfunc with process : y
    Finished myfunc with process : y
    Starting myfunc with process : k
    Finished myfunc with process : k

它不应该像下面那样。

    Starting myfunc with process : x
    Starting myfunc with process : k
    Finished myfunc with process : k
    Starting myfunc with process : z
    Finished myfunc with process : x
    Finished myfunc with process : z

标签: linuxbashshell

解决方案


推荐阅读