LoginSignup
1
0

More than 1 year has passed since last update.

xargsを使ったプロセスの並列化

Last updated at Posted at 2021-06-25

目的

X = \{ apple, orange, grape, ... \} \\
Y = \{ 1, 2, 3, 4, ... \}

としたときのXとYの直積

X \times Y = \{ (apple,1), (apple,2), ..., (orange,1), (orange,2),...\}

の各要素を引数に取るようなプロセスを実行したい。
さらに、論理コアの数だけ並列に実行したい。

実装

# 論理コア数
logic_core_num=12

# 呼び出したいプロセス
function hogeProcess(){
  echo $1 $2
  sleep 5
}

# exportしないとxargsの引数でシェルスクリプト内の関数を呼び出せない
export -f hogeProcess 

# 実行部分
fruits_list=(apple orange grape)
for fruits in ${fruits_list[@]}; \
do \
  for i in `seq 1 32`; \
  do \
    echo $fruits $i; \
  done; \
done | xargs -I arg -P $logic_core_num bash -c "hogeProcess arg"
IFS=$'\n'
echo "${fruits_list[*]}" | xargs -I fruits bash -c "seq 1 32 | xargs -I idx echo fruits idx" | xargs -I arg -P $logic_core_num bash -c "hogeProcess arg"

とワンライナーでも書ける(可読性低いけど)

感想

サーバーのCPUを遊ばせずに多重起動できるようになった。

1
0
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
1
0