微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在bash中并行化for循环限制进程数

我有一个类似于的bash脚本:
NUM_PROCS=$1
NUM_ITERS=$2

for ((i=0; i<$NUM_ITERS; i++)); do
    python foo.py $i arg2 &
done

将并行进程数限制为NUM_PROCS的最简单方法是什么?我正在寻找一种不需要包/安装/模块(如GNU Parallel)的解决方案.

当我尝试Charles Duffy的最新方法时,我从bash -x得到以下错误

+ python run.py args 1
+ python run.py ... 3
+ python run.py ... 4
+ python run.py ... 2
+ read -r line
+ python run.py ... 1
+ read -r line
+ python run.py ... 4
+ read -r line
+ python run.py ... 2
+ read -r line
+ python run.py ... 3
+ read -r line
+ python run.py ... 0
+ read -r line

…继续使用介于0和5之间的其他数字,直到启动了太多进程来处理系统并关闭bash脚本.

作为一个非常简单的实现,取决于bash的新版本足够等待-n(等待只有下一个作业退出,而不是等待所有作业):
#!/bin/bash
#      ^^^^ - NOT /bin/sh!

num_procs=$1
num_iters=$2

for ((i=0; i<num_iters; i++)); do
  while read -r -a curr_jobs < <(jobs -p -r) \
        && (( ${#curr_jobs[@]} >= num_procs )); do
    wait -n
  done
  python foo.py "$i" arg2 &
done

如果在没有等待-n的情况下在shell上运行,则可以(非常低效地)用诸如sleep 0.2之类的命令替换它,以每1/5秒轮询一次.

由于您实际上是在读取文件中的输入,另一种方法是启动N个子进程,每个进程只在其中行(linenum%N == threadnum):

num_procs=$1
infile=$2
for ((i=0; i<num_procs; i++)); do
  (
    while read -r line; do
      echo "Thread $i: processing $line"
    done < <(awk -v num_procs="$num_procs" -v i="$i" \
                 'NR % num_procs == i { print }' <"$infile")
  ) &
done
wait # wait for all $num_procs subprocesses to finish

原文地址:https://www.jb51.cc/bash/387071.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐