Shell中实现“多线程”执行脚本文件完美解决方案
即比如我有100个可执行文件,互相间没有特别的先后执行关系,如CODE:
job_1 job_2 job_2 ..... job_100
想用csh/bash来多线程调用执行。
比如一次开5个线程,那么job_1,2,3,4,5一起先开始,那么其中任何一个线程如果先执行完成,则继续执行下一个没有初执行过的文件,如job_6,7,8....,这样一直以所指定的线程数来执行所有100个文件。
我本来想用"&"来放入后台,可是这样我一次可以指定5放入后台,但是无法知道其中任何一个程序何时执行完毕,所以也无法继续执行下一个程序啊!
完美解决方案:
-(dearvoid@LinuxEden:Forum)-(~/tmp)- [$$=6718$?=0];catjob_1 #!/bin/bash n=$((RANDOM%5+1)) echo"$0sleepingfor$nseconds..." sleep$n echo"$0exiting..." -(dearvoid@LinuxEden:Forum)-(~/tmp)- [$$=6718$?=0];for((i=2;i<=10;++i));docpjob_1job_$i;done -(dearvoid@LinuxEden:Forum)-(~/tmp)- [$$=6718$?=0];catjobs.sh #!/bin/bash nParellel=5 nJobs=10 sJobPattern='./job_%d' aJobs=() sNextJob= for((iNextJob=1;iNextJob<=nJobs;));do for((iJob=0;iJob<nParellel;++iJob));do if[$iNextJob-gt$nJobs];then break; fi if[!"${aJobs[iJob]}"]||!kill-0${aJobs[iJob]}2>/dev/null;then printf-vsNextJob"$sJobPattern"$((iNextJob++)) echo"$sNextJobstarting..." $sNextJob& aJobs[iJob]=$! fi done sleep.1 done wait -(dearvoid@LinuxEden:Forum)-(~/tmp)- [$$=6718$?=0];./jobs.sh ./job_1starting... ./job_1sleepingfor3seconds... ./job_2starting... ./job_2sleepingfor2seconds... ./job_3starting... ./job_3sleepingfor5seconds... ./job_4starting... ./job_5starting... ./job_4sleepingfor4seconds... ./job_5sleepingfor2seconds... ./job_2exiting... ./job_6starting... ./job_6sleepingfor2seconds... ./job_5exiting... ./job_7starting... ./job_7sleepingfor1seconds... ./job_1exiting... ./job_8starting... ./job_8sleepingfor3seconds... ./job_7exiting... ./job_9starting... ./job_9sleepingfor5seconds... ./job_4exiting... ./job_6exiting... ./job_10starting... ./job_10sleepingfor5seconds... ./job_3exiting... ./job_8exiting... ./job_9exiting... ./job_10exiting... -(dearvoid@LinuxEden:Forum)-(~/tmp)- [$$=6718$?=0];bye