#/bin/bash all_num=10 a=$(date +%H%M%S) for num in `seq 1 ${all_num}` do { sleep 1 echo ${num} } & done b=$(date +%H%M%S) echo -e "startTime:\t$a" echo -e "endTime:\t$b"
在命令的末尾加 & 符號,則命令將在後臺執行,這樣後面的命令不須要等待該命令執行完再開始執行。html
#/bin/bash all_num=10 a=$(date +%H%M%S) for num in `seq 1 ${all_num}` do { sleep 1 echo ${num} } & # 將命令在後臺執行,命令範圍用{}包圍 done # 等待當前腳本進程下的子進程結束 wait b=$(date +%H%M%S) echo -e "startTime:\t$a" echo -e "endTime:\t$b"
#/bin/bash all_num=10 # 設置併發的進程數 thread_num=5 a=$(date +%H%M%S) # mkfifo tempfifo="my_temp_fifo" mkfifo ${tempfifo} # 使文件描述符爲非阻塞式 exec 6<>${tempfifo} rm -f ${tempfifo} # 爲文件描述符建立佔位信息 for ((i=1;i<=${thread_num};i++)) do { echo } done >&6 # for num in `seq 1 ${all_num}` do { read -u6 { sleep 1 echo ${num} echo "" >&6 } & } done wait # 關閉fd6管道 exec 6>&- b=$(date +%H%M%S) echo -e "startTime:\t$a" echo -e "endTime:\t$b"
[1] 情景linux--shell如何實現多線程?linux
[2] Linux-Shell-使用mkfifo實現多任務併發及併發數控制shell