如何在循环中运行固定数量的进程?

Spu*_*nky 3 parallel-processing bash wait

我有一个这样的脚本:

#!/bin/bash
for i=1 to 200000
do
create input file
run ./java
done
Run Code Online (Sandbox Code Playgroud)

我需要同时运行多个(8 或 16 个)进程 (java),但我不知道如何运行。我知道这wait会有所帮助,但它应该一直运行 8 个进程,而不是等待前 8 个进程完成后再启动其他 8 个进程。

che*_*ner 5

bash4.3 向wait命令添加了一个有用的新标志,-n,这会导致wait阻塞,直到任何单个后台作业,而不仅仅是给定子集(或所有)的成员,完成。

#!/bin/bash
cores=8  # or 16, or whatever
for ((i=1; i <= 200000; i++))
do
    # create input file and run java in the background.
    ./java &

    # Check how many background jobs there are, and if it
    # is equal to the number of cores, wait for anyone to
    # finish before continuing.
    background=( $(jobs -p) )
    if (( ${#background[@]} == cores )); then
        wait -n
    fi
done
Run Code Online (Sandbox Code Playgroud)

有一个小的竞争条件:如果您处于最大负载但运行后作业完成jobs -p,您仍然会阻塞,直到另一个作业完成。您对此无能为力,但在实践中应该不会带来太多麻烦。


在bash4.3之前,您需要定期轮询后台作业集以查看池何时降至阈值以下。

while :; do
    background=( $(jobs -p))
    if (( ${#background[@]} < cores )); then
        break
    fi
    sleep 1
done
Run Code Online (Sandbox Code Playgroud)