bash - 使用最大进程数并行化 Bash 脚本

标签 bash

假设我在 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/

相关文章:

linux - CGI 脚本不执行 bash 命令,例如 'CP'

bash - "Filename argument required"从 bash_profile 运行 shell 命令时出现警告

c - 如何获取 Mac OS X 的 C 包中所有库的列表?

bash - 'while head -n 1' 好奇心

regex - 如何使用 sed 将第一个空格替换为空字符串

bash - 在 Bash 中解析命令行参数的最佳方式?

linux - 通过 shell 脚本将 "raw"命令行添加到 bashrc(不评估命令)

javascript - Node 中的Linux系统变量

linux - sed: |: 没有那个文件或目录

linux - 在 bash shell 中使用 scp 时出现段错误(核心已转储)