加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-15 16:43:40 所属栏目:安全 来源:网络整理
导读:让我说我有一个循环bash: for foo in `some-command`do do-something $foodone do-something是cpu绑定,我有一个很好的闪亮的4核处理器。我想能够立即运行多达4个do-something。 天真的方法似乎是: for foo in `some-command`do do-something $foo done 这
让我说我有一个循环bash:
for foo in `some-command`
do
   do-something $foo
done

do-something是cpu绑定,我有一个很好的闪亮的4核处理器。我想能够立即运行多达4个do-something。

天真的方法似乎是:

for foo in `some-command`
do
   do-something $foo &
done

这将立即运行所有do-somethings,但有一对夫妇的缺点,主要是做某事,也可能有一些重要的I / O,执行一次可能会放慢一点。另一个问题是这个代码块立即返回,所以没有办法做其他工作,当所有的do-somethings完成。

你怎么写这个循环,所以总是有X做某事一次运行?

根据你想做什么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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读