Forking / Multi-Threaded Processes | Bash

前端 未结 8 1600
被撕碎了的回忆
被撕碎了的回忆 2020-11-30 20:39

I would like to make a section of my code more efficient. I\'m thinking of making it fork off into multiple processes and have them execute 50/100 times at once, instead of

8条回答
  •  情书的邮戳
    2020-11-30 20:55

    I don't know of any explicit fork call in bash. What you probably want to do is append & to a command that you want to run in the background. You can also use & on functions that you define within a bash script:

    do_something_with_line()
    {
      line=$1
      foo
      foo2
      foo3
    }
    
    for line in file
    do
      do_something_with_line $line &
    done
    

    EDIT: to put a limit on the number of simultaneous background processes, you could try something like this:

    for line in file
    do
      while [`jobs | wc -l` -ge 50 ]
      do
        sleep 5
      done
      do_something_with_line $line &
    done
    

提交回复
热议问题