How to bash multithread?

I do think using xargs to run code multithread in bash is a better way, you still could use fifo. Just like the sample below:

#!/bin/bash
function a_sub
{
    sleep 3
}
tmp_fifofile="/tmp/$$.fifo"
mkfifo $tmp_fifofile
exec 6<>$tmp_fifofile

rm $tmp_fifofile

thread=15

for((i=0;i<$thread;i++));do
    echo
done >&6

for((i=0;i<50;i++));do
    read -u 6
    {
        a_sub && {
            echo "a_sub is finished"
        } || {
            echo "sub error"
        }
        echo >&6
    }&
done

exec 6>&-

wait

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.

This site uses Akismet to reduce spam. Learn how your comment data is processed.