Shell中實現“多線程”執行指令檔完美解決方案_linux shell

來源:互聯網
上載者:User

即比如我有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] ; cat job_1
#!/bin/bash
n=$((RANDOM % 5 + 1))
echo "$0 sleeping for $n seconds ..."
sleep $n
echo "$0 exiting ..."
-(dearvoid@LinuxEden:Forum)-(~/tmp)-
[$$=6718 $?=0] ; for ((i = 2; i <= 10; ++i)); do cp job_1 job_$i; done
-(dearvoid@LinuxEden:Forum)-(~/tmp)-
[$$=6718 $?=0] ; cat jobs.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 -v sNextJob "$sJobPattern" $((iNextJob++))
            echo "$sNextJob starting ..."
            $sNextJob &
            aJobs[iJob]=$!
        fi
    done
    sleep .1
done
wait
-(dearvoid@LinuxEden:Forum)-(~/tmp)-
[$$=6718 $?=0] ; ./jobs.sh
./job_1 starting ...
./job_1 sleeping for 3 seconds ...
./job_2 starting ...
./job_2 sleeping for 2 seconds ...
./job_3 starting ...
./job_3 sleeping for 5 seconds ...
./job_4 starting ...
./job_5 starting ...
./job_4 sleeping for 4 seconds ...
./job_5 sleeping for 2 seconds ...
./job_2 exiting ...
./job_6 starting ...
./job_6 sleeping for 2 seconds ...
./job_5 exiting ...
./job_7 starting ...
./job_7 sleeping for 1 seconds ...
./job_1 exiting ...
./job_8 starting ...
./job_8 sleeping for 3 seconds ...
./job_7 exiting ...
./job_9 starting ...
./job_9 sleeping for 5 seconds ...
./job_4 exiting ...
./job_6 exiting ...
./job_10 starting ...
./job_10 sleeping for 5 seconds ...
./job_3 exiting ...
./job_8 exiting ...
./job_9 exiting ...
./job_10 exiting ...
-(dearvoid@LinuxEden:Forum)-(~/tmp)-
[$$=6718 $?=0] ; bye

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.