Skip to content

Instantly share code, notes, and snippets.

@thinkycx
Last active January 14, 2019 05:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thinkycx/f1350b209733afa71523a9f1ec057c96 to your computer and use it in GitHub Desktop.
Save thinkycx/f1350b209733afa71523a9f1ec057c96 to your computer and use it in GitHub Desktop.
#!/bin/bash
# author: thinkycx
# date: 2019-01-14
# Usage:
# run jobs at the same time with multiple process.
parallel(){
nCPU=3 # 同时执行的进程数量
PID=()
for((i=0;i<5;i++)){
# while process number >= nCPU
echo "============================================"
# echo "[*] PID() len: " ${#PID[*]}
echo "[*] PID() content:" ${PID[*]}
# echo "[-] Checking PID() length >= nCPU ?"
while [ ${#PID[*]} -ge $nCPU ] ;
do
for pid in ${PID[*]}; do
ps -p $pid >/dev/null
isQuit=$?
if [ $isQuit -eq 1 ] ; then
PID=(${PID[*]/$pid})
echo "[*] Checking... $pid stops. PID() len: " ${#PID[*]}
fi
done
sleep 1;
done
# echo "[*] After check. " ${PID[*]}
# start new process background
(
echo -e "\\t [x] Job $i start to run..."
sleep 5
echo -e "\\t [x] Job $i done. "
)&
PID[$i]=$! # 向数组中添加上一个运行的后台进程的pid
sleep 1
echo -e "\\t [*] process PID is :" ${PID[$i]}
}
}
parallel
wait
echo "[*] Congratilations. All jobs done! "
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment