一直在找一个bash实现的多线程,虽然这个方法看着不怎么高明,但是比那个fifo的写法,看着明白点。这里面也限制了最多线程数,类似于线程池,记录在此,以备后用。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37  | #!/bin/bash
 
MAX_THREAD_NUM=10;
thread_pids=()
 
#执行线程
function hello_thread(){
    echo "print $1"
    sleep 5;
}
 
#检查是否有完成的线程,把pid剔除调
function check_current_thread(){
    if [ ${#thread_pids[@]} -ne 0 ]; then
        for pid_idx in ${!thread_pids[*]}; do
           pid_val=${thread_pids[$pid_idx]}
           kill -s 0 $pid_val &>/dev/null || unset thread_pids[$pid_idx]
        done
        thread_pids=("${thread_pids[@]}")
    fi;
}
 
for i in {1..100}; do
#如果当前执行的线程数少于10个,就加一个任务
    if [ ${#thread_pids[@]} -lt $MAX_THREAD_NUM ]; then
        hello_thread $i &
        thread_pids=("${thread_pids[@]}" "$!");
    else
        sleep 1;
        check_current_thread;
    fi
done
#等待最后的任务结束
while [ ${#thread_pids[@]} -ne 0 ]; do
    check_current_thread;
    sleep 1;
done; | 
除非注明,赵岩的博客文章均为原创,转载请以链接形式标明本文地址
 本文地址:http://zhaoyanblog.com/archives/620.html  
            
jobs -l 可以了解一下 可以简化逻辑
补充:专业一点的多线程
#!/bin/bash tmp_fifofile=" /tmp/$$.fifo " mkfifo $tmp_fifofile exec 6<>$tmp_fifofile rm $tmp_fifofile #线程个数 thread=2 for (( i=0 ;i < $thread ;i++ )); do echo done >&6 //你的任务队列 for ((i=0;i<100; i++)) read -u6 { //todo 你的逻辑任务 echo >&6 }& done wait exec 6>&- exit 0