How to run given function in Bash in parallel?

后端 未结 3 979
故里飘歌
故里飘歌 2021-01-30 14:00

There have been some similar questions, but my problem is not \"run several programs in parallel\" - which can be trivially done with parallel or xargs

3条回答
  •  野性不改
    2021-01-30 14:36

    sem is part of GNU Parallel and is made for this kind of situation.

    for i in "${list[@]}"
    do
        for j in "${other[@]}"
        do
            # some processing in here - 20-30 lines of almost pure bash
            sem -j 4 dolong task
        done
    done
    

    If you like the function better GNU Parallel can do the dual for loop in one go:

    dowork() { 
      echo "Starting i=$1, j=$2"
      sleep 5
      echo "Done i=$1, j=$2"
    }
    export -f dowork
    
    parallel dowork ::: "${list[@]}" ::: "${other[@]}"
    

提交回复
热议问题