我有一个这样的脚本:
#!/bin/bash
for i=1 to 200000
do
create input file
run ./java
done
我需要同时运行多个(8 或 16)个进程(java),但我不知道如何运行。我知道wait
可以提供帮助,但它应该始终运行 8 个进程,而不是等待前 8 个进程完成后再启动其他 8 个进程。
bash
4.3 添加了一个有用的新标志wait
命令,-n
, 什么导致wait
阻止直到any单个后台作业,而不仅仅是给定子集(或全部)的成员来完成。
#!/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
有一个小的竞争条件:如果您处于最大负载但作业已完成after你跑jobs -p
,你仍然会阻塞直到另一份工作
完成。您对此无能为力,但在实践中不会带来太多麻烦。
之前bash
4.3 中,您需要定期轮询后台作业集,以查看池何时降至阈值以下。
while :; do
background=( $(jobs -p))
if (( ${#background[@]} < cores )); then
break
fi
sleep 1
done
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)