LoginSignup
4
1

More than 3 years have passed since last update.

bash: バックグランドジョブの数を制限する

Last updated at Posted at 2016-02-27
#!/bin/bash

# ジョブ数が$1未満になるまでブロックする
wait_until_jobn_lt () {
  local max_jobn=$1
  while [[ "$(jobs | wc -l)" -ge "$max_jobn" ]] ; do
    #       実行中のジョブ数    >=   最大ジョブ数  
    sleep 1
  done
}

# デモ用ジョブ (数秒sleepするだけ)
start_dummy_job () {
  local title="job #$1"
  echo "$(date) starting $title"
  sleep $(( 1 + $RANDOM % 5 ))
  echo "$(date) finished $title"
}

for job_no in {1..5} ; do
  wait_until_jobn_lt $(nproc)
  #                  ^プロセッサー数
  start_dummy_job $job_no &
done
wait
echo "all finished"

(2コアPCの場合こんな感じになる)

Sat Feb 27 22:28:54 JST 2016 starting job #1
Sat Feb 27 22:28:54 JST 2016 starting job #2
Sat Feb 27 22:28:56 JST 2016 finished job #1
Sat Feb 27 22:28:56 JST 2016 starting job #3
Sat Feb 27 22:28:57 JST 2016 finished job #2
Sat Feb 27 22:28:57 JST 2016 starting job #4
Sat Feb 27 22:29:01 JST 2016 finished job #3
Sat Feb 27 22:29:01 JST 2016 finished job #4
Sat Feb 27 22:29:01 JST 2016 starting job #5
Sat Feb 27 22:29:06 JST 2016 finished job #5
all finished
4
1
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
4
1