3
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

メモ:複数のコマンドを並列実行する簡易コマンド

Last updated at Posted at 2019-04-09

GNU parallelをインストールせずに並列実行を実現したかったので、そのとき作ったShellのメモ

ちなみにGNU parallelを使った場合はこんなかんじ

% time parallel -j 2 {} << EOF
  echo 1;sleep 5;
  echo 2;sleep 5;
EOF
1
2
parallel -j 2 {} <<<'  echo 1;sleep 5;     echo 2;sleep 5;'  0.22s user 0.23s system 8% cpu 5.500 total

処理部分

CPU_CORE=2
parallel_exec () {
  for i in "$@"; do echo $i; done | xargs -I{} -P ${CPU_CORE} sh -c {}
}

使用方法

parallel_exec "コマンド1" "コマンド2"

使用例

$ parallel_exec "echo hoge" "echo foo"
hoge
foo

実行時間計測結果

$ time parallel_exec "sleep 3; echo hoge" "sleep 1; echo foo"
foo
hoge

real	0m3.021s
user	0m0.011s
sys	0m0.014s

sleep 1の foo が先に出力され、全体の実行時間も約3秒なので期待通り。

エラー時の挙動

ちなみにスクリプト中のコマンドでエラーが発生すると parallel_exec 自体もエラーコードを返してくれる

$ parallel_exec "sleep 3; exit 0" "sleep 1; exit 1"
$ echo $?
1
3
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?