You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Shell代码在多线程中运行带不同参数的同一程序实例?

让Shell测试脚本并行运行的几种方法

方法1:后台运行每个命令(最简易)

直接在每个测试命令末尾添加&,让进程在后台独立运行,最后用wait命令等待所有后台进程执行完毕:

./program inputFile1 outputFile1 &
./program inputFile2 outputFile2 &
./program inputFile3 outputFile3 &
./program inputFile4 outputFile4 &
wait
  • 优点:无需额外工具,写法简单直接
  • 注意:如果测试用例数量过多,会一次性启动大量进程,可能耗尽系统资源,反而降低整体运行效率

方法2:用xargs控制并发数

如果需要限制同时运行的进程数量,避免资源过载,可以借助xargs工具:

  1. 先把所有测试命令写入一个文本文件(比如tests.txt),每行一条命令:
./program inputFile1 outputFile1
./program inputFile2 outputFile2
./program inputFile3 outputFile3
./program inputFile4 outputFile4
  1. 用xargs指定并发数执行:
xargs -n 1 -P 4 sh -c < tests.txt
  • -n 1:每次读取一行作为一个独立命令执行
  • -P 4:最多同时运行4个进程(可根据CPU核心数调整)
  • 优点:精准控制并发数,避免系统资源被占满

方法3:用parallel工具(更灵活)

如果系统已安装parallel工具(多数Linux发行版可通过包管理器安装,比如apt install parallel),可以实现更灵活的并行控制:

  • 直接列出命令执行:
parallel ::: \
"./program inputFile1 outputFile1" \
"./program inputFile2 outputFile2" \
"./program inputFile3 outputFile3" \
"./program inputFile4 outputFile4"
  • 从文件读取命令执行:
parallel < tests.txt
  • 还支持按规律批量生成命令(如果输入输出文件名有统一格式):
parallel ./program inputFile{} outputFile{} ::: 1 2 3 4
  • 用-j参数指定并发数,比如-j 4表示同时运行4个进程
  • 优点:功能丰富,支持复杂的批量处理场景

内容的提问来源于stack exchange,提问作者Lucy Janssens

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 22:45:27