#!/bin/bash

# Code to run a bunch of threads in parallel.
# You tell it what to run on the standard input.

t=$1
trap "rm -rf $t" EXIT

mkdir -p $t
NP=$2
oom_adj=$3

declare -a running
running=( )
i=0
while read args
do
  i=$(($i+1))
  # eval $args  >$t/new$i 2>&1 &
  $args  >$t/new$i 2>&1 &
  pid=$!
  running[${#running[*]}]=$pid
  echo $oom_adj > /proc/$pid/oom_adj
  sleep 1 && mv $t/new$i $t/$pid

  while [[ ${#running[*]} -ge $NP ]]
  do
    w=${running[0]}
    running=( ${running[@]:1} )
    if wait $w
    then
      cat $t/$w && { rm $t/$w & }
    else
      cat $t/$w && { rm $t/$w & }
      die.sh "Exec $w" || exit 1
    fi
  done
done

while [[ ${#running[*]} -gt 0 ]]
do
  w=${running[0]}
  running=( ${running[@]:1} )
  wait $w || die.sh "Exec $w" || exit 1
  cat $t/$w && { rm $t/$w & }
done
