Created
June 6, 2017 10:53
-
-
Save sromku/ce87b12c389d9708aa0e0446a50637b6 to your computer and use it in GitHub Desktop.
Control number of parallel 'threads' to be able execute and keep the in pool
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# params | |
num=20 # total tests | |
threads=5 # parallel processes | |
# for script | |
readonly CONST_NAN_PID=-1 | |
# return 0 (true) if PID is running, otherwise return 1 (false) | |
isPIDup() { | |
if [ $1 -eq $CONST_NAN_PID ]; then | |
return 1 | |
fi | |
if ps -p $1 > /dev/null | |
then | |
return 0 | |
else | |
return 1 | |
fi | |
} | |
# prepare | |
pool=() | |
for ((i=0;i<$threads;i++)); do | |
pool[i]=$CONST_NAN_PID | |
done | |
i=0 | |
while true; do | |
thread=-1 | |
for pi in "${!pool[@]}" | |
do | |
pid=${pool[$pi]} | |
if ! isPIDup $pid; then | |
thread=$pi | |
break | |
fi | |
done | |
# if all process running and we didn't found idle thread -> check again later | |
if [ $thread -eq -1 ]; then | |
sleep 0.1 | |
continue | |
fi | |
# if we already tested all tests | |
if [ $i -eq $num ] ; then | |
break | |
fi | |
# start the test of 5 seconds | |
executeTime=$[ ( $RANDOM % 5 ) + 1 ] | |
sleep $executeTime & | |
pid=$! | |
echo "Running: $i - time: $executeTime, thread: $thread, pid: $pid" | |
pool[$thread]=$pid | |
# increase to next one | |
i=$(( $i + 1 )) | |
done | |
# looks like we are fine | |
echo "DONE" | |
echo "" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment