Open multiple sub-processes in the script with & background, and use the wait command to make these sub-processes execute in parallel.
Example 1:
fun1 () {whiletruedoesecho1sleep1done }fun2 () {whiletruedoecho2sleep 1 Done &&Wait
Example 2:
#!/bin/Bash for((i=0;i<5; i++)) DoSleep 3;Echoa Done#运行需要15秒. #!/bin/Bash for((i=0;i<5; i++)) Do{Sleep 3;EchoA}& Donewait#打开5个子进程并行, it only takes 3 seconds to run.
Example 3:
Use pipeline FIFO file to handle concurrency, this example goes from https://my.oschina.net/sanpeterguo/blog/133304
This example allows bloggers to learn a lot, using the pipeline, read-u,exec related knowledge, follow-up blog updated gradually.
#!/bin/bash#author: [Email protected]#Date:2013.05. -#sub Process Dosomethingfunctiona_sub_process {Echo "processing in PID [$$]" Sleep 1} #创建一个fifo文件FIFO_FILE=/tmp/$.fifoMkfifo$FIFO _file# associated FIFO files and fd6exec6<>$FIFO _file # fd6 point to FIFO typeRM$FIFO _file# Maximum number of processes Process_num=4#向fd6中输入 $PROCESS _num a carriage return . for((idx=0;idx< $PROCESS _num;idx++)); Do Echo Done>&6#处理业务, you can use the while for((idx=0;idx< -; idx++)); DoRead-u6 #read-The U6 command executes once, which is equivalent to trying to get a row from fd6, and if it is not, blocks the #获取到了一行后, fd6 a line, starts processing the child process, and the child process executes in the background {a_sub_process&& { Echo "Sub_process is finished" } || { Echo "Sub Error"#完成后再补充一个回车到fd6中, release a lockEcho>&6# when the process is finished, add a carriage return to the FD6, that is, fill in the read-U6 minus the one}& Done#关闭fd6exec6>&-
Shell--wait and multi-process concurrency