linux shell创建进程数,如何在bash中并行化for循环限制进程数

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

#!/bin/bash

# ^^^^ - NOT /bin/sh!

num_procs=$1

num_iters=$2

for ((i=0; i

while read -r -a curr_jobs <

&& (( ${#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

(

while read -r line; do

echo "Thread $i: processing $line"

done <

'NR % num_procs == i { print }'

) &

done

wait # wait for all $num_procs subprocesses to finish