假设我在 Bash 中有一个循环:
for foo in `some-command`
do
do-something $foo
done
do-something
受 cpu 限制,我有一个漂亮 Shiny 的 4 核处理器。我希望能够同时运行多达 4 个 do-something
。
天真的做法似乎是:
for foo in `some-command`
do
do-something $foo &
done
这将同时运行所有 do-something
,但有一些缺点,主要是 do-something 可能还有一些重要的 I/O 执行所有 一次可能会慢一点。另一个问题是此代码块会立即返回,因此在所有 do-something
完成后无法执行其他工作。
您将如何编写此循环,以便总是同时运行 X 个 do-something
?
最佳答案
根据您想执行的操作,xargs 也可以提供帮助(此处:使用 pdf2ps 转换文档):
cpus=$( ls -d /sys/devices/system/cpu/cpu[[:digit:]]* | wc -w )
find . -name \*.pdf | xargs --max-args=1 --max-procs=$cpus pdf2ps
来自文档:
--max-procs=max-procs
-P max-procs
Run up to max-procs processes at a time; the default is 1.
If max-procs is 0, xargs will run as many processes as possible at a
time. Use the -n option with -P; otherwise chances are that only one
exec will be done.
关于bash - 使用最大进程数并行化 Bash 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38160/