How to run given function in Bash in parallel?

后端 未结 3 953
故里飘歌
故里飘歌 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:26

    Edit: Please consider Ole's answer instead.

    Instead of a separate script, you can put your code in a separate bash function. You can then export it, and run it via xargs:

    #!/bin/bash
    dowork() { 
        sleep $((RANDOM % 10 + 1))
        echo "Processing i=$1, j=$2"
    }
    export -f dowork
    
    for i in "${list[@]}"
    do
        for j in "${other[@]}"
        do
            printf "%s\0%s\0" "$i" "$j"
        done
    done | xargs -0 -n 2 -P 4 bash -c 'dowork "$@"' -- 
    

提交回复
热议问题